Line data Source code
1 : import type { Point2D, Size2D } from '@comfyorg/shared-frontend-utils/geometry'
2 : import * as d from 'typegpu/data'
3 : import { StrokePoint } from './gpuSchema'
4 : import {
5 : brushFragment,
6 : brushVertex,
7 : blitShader,
8 : compositeShader,
9 : readbackShader
10 : } from './brushShaders'
11 :
12 : // ... (rest of the file)
13 :
14 29 : const QUAD_VERTS = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1])
15 29 : const QUAD_INDICES = new Uint16Array([0, 1, 2, 0, 2, 3])
16 :
17 29 : const UNIFORM_SIZE = 48 // Uniform buffer size aligned to 16 bytes
18 29 : const STROKE_STRIDE = d.sizeOf(StrokePoint) // 16
19 29 : const MAX_STROKES = 10000
20 :
21 29 : export class GPUBrushRenderer {
22 : private device: GPUDevice
23 :
24 : // Buffers
25 : private quadVertexBuffer: GPUBuffer
26 : private indexBuffer: GPUBuffer
27 : private instanceBuffer: GPUBuffer
28 : private uniformBuffer: GPUBuffer
29 :
30 : // Pipelines
31 : private renderPipeline: GPURenderPipeline // Standard alpha blending pipeline
32 : private accumulatePipeline: GPURenderPipeline // Maximum coverage pipeline for stroke accumulation
33 : private blitPipeline: GPURenderPipeline
34 : private compositePipeline: GPURenderPipeline // Composite pipeline that applies opacity
35 : private compositePipelinePreview: GPURenderPipeline // Pipeline for rendering to the preview canvas
36 : private erasePipeline: GPURenderPipeline // Pipeline for erasing (Destination Out)
37 : private erasePipelinePreview: GPURenderPipeline // Eraser pipeline for the preview canvas
38 : readbackPipeline: GPUComputePipeline // Compute pipeline for texture readback
39 :
40 : // Bind Group Layouts
41 : private uniformBindGroupLayout: GPUBindGroupLayout
42 : private textureBindGroupLayout: GPUBindGroupLayout
43 :
44 : // Shared Bind Groups
45 : private mainUniformBindGroup: GPUBindGroup
46 :
47 : // Textures
48 : private currentStrokeTexture: GPUTexture | null = null
49 : private currentStrokeView: GPUTextureView | null = null
50 :
51 : // Cached Bind Groups
52 : private compositeTextureBindGroup: GPUBindGroup | null = null
53 : private previewTextureBindGroup: GPUBindGroup | null = null
54 :
55 : // Removed separate uniform bind groups as we will use mainUniformBindGroup
56 :
57 : private lastReadbackTexture: GPUTexture | null = null
58 : private lastReadbackBuffer: GPUBuffer | null = null
59 : private readbackBindGroup: GPUBindGroup | null = null
60 :
61 : private lastBackgroundTexture: GPUTexture | null = null
62 : private backgroundBindGroup: GPUBindGroup | null = null
63 :
64 : constructor(
65 : device: GPUDevice,
66 : presentationFormat: GPUTextureFormat = 'rgba8unorm'
67 : ) {
68 0 : this.device = device
69 :
70 : // --- 1. Initialize Buffers ---
71 0 : this.quadVertexBuffer = device.createBuffer({
72 : size: QUAD_VERTS.byteLength,
73 : usage: GPUBufferUsage.VERTEX,
74 : mappedAtCreation: true
75 : })
76 0 : new Float32Array(this.quadVertexBuffer.getMappedRange()).set(QUAD_VERTS)
77 0 : this.quadVertexBuffer.unmap()
78 :
79 0 : this.indexBuffer = device.createBuffer({
80 : size: QUAD_INDICES.byteLength,
81 : usage: GPUBufferUsage.INDEX,
82 : mappedAtCreation: true
83 : })
84 0 : new Uint16Array(this.indexBuffer.getMappedRange()).set(QUAD_INDICES)
85 0 : this.indexBuffer.unmap()
86 :
87 0 : this.instanceBuffer = device.createBuffer({
88 : size: MAX_STROKES * STROKE_STRIDE,
89 : usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
90 : })
91 :
92 0 : this.uniformBuffer = device.createBuffer({
93 : size: UNIFORM_SIZE,
94 : usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
95 : })
96 :
97 : // --- 2. Brush Shader (Drawing) ---
98 0 : const brushModuleV = device.createShaderModule({ code: brushVertex })
99 0 : const brushModuleF = device.createShaderModule({ code: brushFragment })
100 :
101 : // Create explicit bind group layouts
102 0 : this.uniformBindGroupLayout = device.createBindGroupLayout({
103 : entries: [
104 : {
105 : binding: 0,
106 : visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
107 : buffer: { type: 'uniform' }
108 : }
109 : ]
110 : })
111 :
112 0 : this.textureBindGroupLayout = device.createBindGroupLayout({
113 : entries: [
114 : {
115 : binding: 0,
116 : visibility: GPUShaderStage.FRAGMENT,
117 : texture: {} // default is float, 2d
118 : }
119 : ]
120 : })
121 :
122 0 : this.mainUniformBindGroup = device.createBindGroup({
123 : layout: this.uniformBindGroupLayout,
124 : entries: [{ binding: 0, resource: { buffer: this.uniformBuffer } }]
125 : })
126 :
127 0 : const renderPipelineLayout = device.createPipelineLayout({
128 : bindGroupLayouts: [this.uniformBindGroupLayout]
129 : })
130 :
131 : // Standard Render Pipeline (Alpha Blend)
132 0 : this.renderPipeline = device.createRenderPipeline({
133 : layout: renderPipelineLayout,
134 : vertex: {
135 : module: brushModuleV,
136 : entryPoint: 'vs',
137 : buffers: [
138 : {
139 : arrayStride: 8,
140 : stepMode: 'vertex',
141 : attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] // Quad vertex attributes
142 : },
143 : {
144 : arrayStride: 16,
145 : stepMode: 'instance',
146 : attributes: [
147 : { shaderLocation: 1, offset: 0, format: 'float32x2' }, // Instance attributes: position
148 : { shaderLocation: 2, offset: 8, format: 'float32' }, // size
149 : { shaderLocation: 3, offset: 12, format: 'float32' } // pressure
150 : ]
151 : }
152 : ]
153 : },
154 : fragment: {
155 : module: brushModuleF,
156 : entryPoint: 'fs',
157 : targets: [
158 : {
159 : format: 'rgba8unorm',
160 : blend: {
161 : color: {
162 : srcFactor: 'one',
163 : dstFactor: 'one-minus-src-alpha',
164 : operation: 'add'
165 : },
166 : alpha: {
167 : srcFactor: 'one',
168 : dstFactor: 'one-minus-src-alpha',
169 : operation: 'add'
170 : }
171 : }
172 : }
173 : ]
174 : },
175 : primitive: { topology: 'triangle-list' }
176 : })
177 :
178 : // Keep the highest coverage reached by each stroke sample.
179 0 : this.accumulatePipeline = device.createRenderPipeline({
180 : layout: renderPipelineLayout,
181 : vertex: {
182 : module: brushModuleV,
183 : entryPoint: 'vs',
184 : buffers: [
185 : {
186 : arrayStride: 8,
187 : stepMode: 'vertex',
188 : attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }]
189 : },
190 : {
191 : arrayStride: 16,
192 : stepMode: 'instance',
193 : attributes: [
194 : { shaderLocation: 1, offset: 0, format: 'float32x2' },
195 : { shaderLocation: 2, offset: 8, format: 'float32' },
196 : { shaderLocation: 3, offset: 12, format: 'float32' }
197 : ]
198 : }
199 : ]
200 : },
201 : fragment: {
202 : module: brushModuleF,
203 : entryPoint: 'fs',
204 : targets: [
205 : {
206 : format: 'rgba8unorm',
207 : blend: {
208 : color: {
209 : srcFactor: 'one',
210 : dstFactor: 'one',
211 : operation: 'max'
212 : },
213 : alpha: {
214 : srcFactor: 'one',
215 : dstFactor: 'one',
216 : operation: 'max'
217 : }
218 : }
219 : }
220 : ]
221 : },
222 : primitive: { topology: 'triangle-list' }
223 : })
224 :
225 : // --- 3. Blit Pipeline (For Preview) ---
226 0 : const blitPipelineLayout = device.createPipelineLayout({
227 : bindGroupLayouts: [this.textureBindGroupLayout]
228 : })
229 :
230 0 : this.blitPipeline = device.createRenderPipeline({
231 : layout: blitPipelineLayout,
232 : vertex: {
233 : module: device.createShaderModule({ code: blitShader }),
234 : entryPoint: 'vs'
235 : },
236 : fragment: {
237 : module: device.createShaderModule({ code: blitShader }),
238 : entryPoint: 'fs',
239 : targets: [
240 : {
241 : format: presentationFormat, // Use the presentation format
242 : blend: {
243 : color: {
244 : srcFactor: 'one',
245 : dstFactor: 'one-minus-src-alpha',
246 : operation: 'add'
247 : },
248 : alpha: {
249 : srcFactor: 'one',
250 : dstFactor: 'one-minus-src-alpha',
251 : operation: 'add'
252 : }
253 : }
254 : }
255 : ]
256 : },
257 : primitive: { topology: 'triangle-list' }
258 : })
259 :
260 : // --- 4. Composite Pipeline ---
261 :
262 0 : const compositePipelineLayout = device.createPipelineLayout({
263 : bindGroupLayouts: [
264 : this.textureBindGroupLayout,
265 : this.uniformBindGroupLayout
266 : ]
267 : })
268 :
269 : // Standard composite pipeline for offscreen textures
270 0 : this.compositePipeline = device.createRenderPipeline({
271 : layout: compositePipelineLayout,
272 : vertex: {
273 : module: device.createShaderModule({ code: compositeShader }),
274 : entryPoint: 'vs'
275 : },
276 : fragment: {
277 : module: device.createShaderModule({ code: compositeShader }),
278 : entryPoint: 'fs',
279 : targets: [
280 : {
281 : format: 'rgba8unorm',
282 : blend: {
283 : color: {
284 : srcFactor: 'one',
285 : dstFactor: 'one-minus-src-alpha',
286 : operation: 'add'
287 : },
288 : alpha: {
289 : srcFactor: 'one',
290 : dstFactor: 'one-minus-src-alpha',
291 : operation: 'add'
292 : }
293 : }
294 : }
295 : ]
296 : },
297 : primitive: { topology: 'triangle-list' }
298 : })
299 :
300 : // Composite pipeline for the preview canvas
301 0 : this.compositePipelinePreview = device.createRenderPipeline({
302 : layout: compositePipelineLayout,
303 : vertex: {
304 : module: device.createShaderModule({ code: compositeShader }),
305 : entryPoint: 'vs'
306 : },
307 : fragment: {
308 : module: device.createShaderModule({ code: compositeShader }),
309 : entryPoint: 'fs',
310 : targets: [
311 : {
312 : format: presentationFormat,
313 : blend: {
314 : color: {
315 : srcFactor: 'one',
316 : dstFactor: 'one-minus-src-alpha',
317 : operation: 'add'
318 : },
319 : alpha: {
320 : srcFactor: 'one',
321 : dstFactor: 'one-minus-src-alpha',
322 : operation: 'add'
323 : }
324 : }
325 : }
326 : ]
327 : },
328 : primitive: { topology: 'triangle-list' }
329 : })
330 :
331 : // --- 5. Erase Pipeline (Destination Out) ---
332 : // Standard erase pipeline for offscreen textures
333 0 : this.erasePipeline = device.createRenderPipeline({
334 : layout: compositePipelineLayout,
335 : vertex: {
336 : module: device.createShaderModule({ code: compositeShader }),
337 : entryPoint: 'vs'
338 : },
339 : fragment: {
340 : module: device.createShaderModule({ code: compositeShader }),
341 : entryPoint: 'fs',
342 : targets: [
343 : {
344 : format: 'rgba8unorm',
345 : blend: {
346 : color: {
347 : srcFactor: 'zero',
348 : dstFactor: 'one-minus-src-alpha', // dst * (1 - src_alpha)
349 : operation: 'add'
350 : },
351 : alpha: {
352 : srcFactor: 'zero',
353 : dstFactor: 'one-minus-src-alpha', // dst_alpha * (1 - src_alpha)
354 : operation: 'add'
355 : }
356 : }
357 : }
358 : ]
359 : },
360 : primitive: { topology: 'triangle-list' }
361 : })
362 :
363 : // Erase pipeline for the preview canvas
364 0 : this.erasePipelinePreview = device.createRenderPipeline({
365 : layout: compositePipelineLayout,
366 : vertex: {
367 : module: device.createShaderModule({ code: compositeShader }),
368 : entryPoint: 'vs'
369 : },
370 : fragment: {
371 : module: device.createShaderModule({ code: compositeShader }),
372 : entryPoint: 'fs',
373 : targets: [
374 : {
375 : format: presentationFormat,
376 : blend: {
377 : color: {
378 : srcFactor: 'zero',
379 : dstFactor: 'one-minus-src-alpha',
380 : operation: 'add'
381 : },
382 : alpha: {
383 : srcFactor: 'zero',
384 : dstFactor: 'one-minus-src-alpha',
385 : operation: 'add'
386 : }
387 : }
388 : }
389 : ]
390 : },
391 : primitive: { topology: 'triangle-list' }
392 : })
393 :
394 : // --- 6. Readback Pipeline (Compute) ---
395 0 : this.readbackPipeline = device.createComputePipeline({
396 : layout: 'auto',
397 : compute: {
398 : module: device.createShaderModule({ code: readbackShader }),
399 : entryPoint: 'main'
400 : }
401 : })
402 : }
403 :
404 : public prepareStroke(width: number, height: number) {
405 : // Initialize or resize the accumulation texture
406 0 : if (
407 : !this.currentStrokeTexture ||
408 : this.currentStrokeTexture.width !== width ||
409 : this.currentStrokeTexture.height !== height
410 : ) {
411 0 : if (this.currentStrokeTexture) this.currentStrokeTexture.destroy()
412 0 : this.currentStrokeTexture = this.device.createTexture({
413 : size: [width, height],
414 : format: 'rgba8unorm',
415 : usage:
416 : GPUTextureUsage.RENDER_ATTACHMENT |
417 : GPUTextureUsage.TEXTURE_BINDING |
418 : GPUTextureUsage.COPY_SRC
419 : })
420 0 : this.currentStrokeView = this.currentStrokeTexture.createView()
421 :
422 : // Invalidate texture-dependent bind groups
423 0 : this.compositeTextureBindGroup = null
424 0 : this.previewTextureBindGroup = null
425 : // Readback bind group might also be invalid if it was using the old texture
426 0 : if (this.lastReadbackTexture === this.currentStrokeTexture) {
427 0 : this.readbackBindGroup = null
428 0 : this.lastReadbackTexture = null
429 : }
430 : }
431 :
432 : // Clear the accumulation texture
433 0 : const encoder = this.device.createCommandEncoder()
434 : const pass = encoder.beginRenderPass({
435 : colorAttachments: [
436 : {
437 : view: this.currentStrokeView!,
438 : loadOp: 'clear',
439 : clearValue: { r: 0, g: 0, b: 0, a: 0 },
440 : storeOp: 'store'
441 : }
442 : ]
443 : })
444 0 : pass.end()
445 0 : this.device.queue.submit([encoder.finish()])
446 : }
447 :
448 : public renderStrokeToAccumulator(
449 : points: (Point2D & { pressure: number })[],
450 : settings: Size2D & {
451 : size: number
452 : coverage: number
453 : hardness: number
454 : color: [number, number, number]
455 : brushShape: number
456 : }
457 : ) {
458 0 : if (!this.currentStrokeView) return
459 :
460 0 : this.renderStrokeInternal(
461 : this.currentStrokeView,
462 : this.accumulatePipeline,
463 : points,
464 : { ...settings, opacity: settings.coverage }
465 : )
466 : }
467 :
468 : public compositeStroke(
469 : targetView: GPUTextureView,
470 : settings: {
471 : opacity: number
472 : color: [number, number, number]
473 : hardness: number // Required for uniform buffer layout
474 : screenSize: [number, number]
475 : brushShape: number
476 : isErasing?: boolean
477 : }
478 : ) {
479 0 : if (!this.currentStrokeTexture) return
480 :
481 : // Update uniforms for the composite pass
482 0 : const buffer = new ArrayBuffer(UNIFORM_SIZE)
483 0 : const f32 = new Float32Array(buffer)
484 0 : const u32 = new Uint32Array(buffer)
485 :
486 0 : f32[0] = settings.color[0]
487 0 : f32[1] = settings.color[1]
488 0 : f32[2] = settings.color[2]
489 0 : f32[3] = settings.opacity
490 0 : f32[4] = settings.hardness
491 0 : f32[5] = 0 // Padding
492 0 : f32[6] = settings.screenSize[0]
493 0 : f32[7] = settings.screenSize[1]
494 0 : u32[8] = settings.brushShape // Brush shape: 0=Circle, 1=Square
495 0 : this.device.queue.writeBuffer(this.uniformBuffer, 0, buffer)
496 :
497 0 : const encoder = this.device.createCommandEncoder()
498 :
499 : // Choose pipeline based on operation
500 0 : const pipeline = settings.isErasing
501 : ? this.erasePipeline
502 : : this.compositePipeline
503 :
504 : // 1. Texture Bind Group (Group 0)
505 0 : if (!this.compositeTextureBindGroup) {
506 0 : this.compositeTextureBindGroup = this.device.createBindGroup({
507 : layout: this.textureBindGroupLayout,
508 : entries: [
509 : { binding: 0, resource: this.currentStrokeTexture.createView() }
510 : ]
511 : })
512 : }
513 :
514 : // 2. Uniform Bind Group (Group 1) - Use shared mainUniformBindGroup
515 : // It is compatible because we used the same layout
516 :
517 0 : const pass = encoder.beginRenderPass({
518 : colorAttachments: [
519 : {
520 : view: targetView,
521 : loadOp: 'load',
522 : storeOp: 'store'
523 : }
524 : ]
525 : })
526 :
527 0 : pass.setPipeline(pipeline)
528 0 : pass.setBindGroup(0, this.compositeTextureBindGroup)
529 0 : pass.setBindGroup(1, this.mainUniformBindGroup)
530 0 : pass.draw(3)
531 0 : pass.end()
532 :
533 0 : this.device.queue.submit([encoder.finish()])
534 : }
535 :
536 : public renderStroke(
537 : targetView: GPUTextureView,
538 : points: (Point2D & { pressure: number })[],
539 : settings: Size2D & {
540 : size: number
541 : opacity: number
542 : hardness: number
543 : color: [number, number, number]
544 : brushShape: number
545 : }
546 : ) {
547 0 : this.renderStrokeInternal(targetView, this.renderPipeline, points, settings)
548 : }
549 :
550 : private renderStrokeInternal(
551 : targetView: GPUTextureView,
552 : pipeline: GPURenderPipeline,
553 : points: (Point2D & { pressure: number })[],
554 : settings: Size2D & {
555 : size: number
556 : opacity: number
557 : hardness: number
558 : color: [number, number, number]
559 : brushShape: number
560 : }
561 : ) {
562 0 : if (points.length === 0) return
563 :
564 0 : const buffer = new ArrayBuffer(UNIFORM_SIZE)
565 0 : const f32 = new Float32Array(buffer)
566 0 : const u32 = new Uint32Array(buffer)
567 :
568 0 : f32[0] = settings.color[0]
569 0 : f32[1] = settings.color[1]
570 0 : f32[2] = settings.color[2]
571 0 : f32[3] = settings.opacity
572 0 : f32[4] = settings.hardness
573 0 : f32[5] = 0
574 0 : f32[6] = settings.width
575 0 : f32[7] = settings.height
576 0 : u32[8] = settings.brushShape
577 0 : this.device.queue.writeBuffer(this.uniformBuffer, 0, buffer)
578 :
579 0 : let processedPoints = 0
580 0 : while (processedPoints < points.length) {
581 0 : const batchSize = Math.min(points.length - processedPoints, MAX_STROKES)
582 0 : const iData = new Float32Array(batchSize * 4)
583 :
584 0 : for (let i = 0; i < batchSize; i++) {
585 0 : const p = points[processedPoints + i]
586 0 : iData[i * 4 + 0] = p.x
587 0 : iData[i * 4 + 1] = p.y
588 0 : iData[i * 4 + 2] = settings.size
589 0 : iData[i * 4 + 3] = p.pressure
590 : }
591 :
592 0 : this.device.queue.writeBuffer(this.instanceBuffer, 0, iData)
593 :
594 0 : const encoder = this.device.createCommandEncoder()
595 0 : const pass = encoder.beginRenderPass({
596 : colorAttachments: [
597 : {
598 : view: targetView,
599 : loadOp: 'load',
600 : storeOp: 'store'
601 : }
602 : ]
603 : })
604 :
605 0 : pass.setPipeline(pipeline)
606 0 : pass.setBindGroup(0, this.mainUniformBindGroup)
607 0 : pass.setVertexBuffer(0, this.quadVertexBuffer)
608 0 : pass.setVertexBuffer(1, this.instanceBuffer)
609 0 : pass.setIndexBuffer(this.indexBuffer, 'uint16')
610 0 : pass.drawIndexed(6, batchSize)
611 0 : pass.end()
612 :
613 0 : this.device.queue.submit([encoder.finish()])
614 :
615 0 : processedPoints += batchSize
616 : }
617 : }
618 :
619 : // Blit the accumulated stroke to the preview canvas
620 : public blitToCanvas(
621 : destinationCtx: GPUCanvasContext,
622 : settings: {
623 : opacity: number
624 : color: [number, number, number]
625 : hardness: number
626 : screenSize: [number, number]
627 : brushShape: number
628 : isErasing?: boolean
629 : },
630 : backgroundTexture?: GPUTexture
631 : ) {
632 0 : const encoder = this.device.createCommandEncoder()
633 0 : const destView = destinationCtx.getCurrentTexture().createView()
634 :
635 0 : if (backgroundTexture) {
636 : // Draw background texture to allow erasing effect on existing content
637 0 : if (
638 : this.lastBackgroundTexture !== backgroundTexture ||
639 : !this.backgroundBindGroup
640 : ) {
641 0 : this.backgroundBindGroup = this.device.createBindGroup({
642 : layout: this.textureBindGroupLayout,
643 : entries: [{ binding: 0, resource: backgroundTexture.createView() }]
644 : })
645 0 : this.lastBackgroundTexture = backgroundTexture
646 : }
647 :
648 0 : const pass = encoder.beginRenderPass({
649 : colorAttachments: [
650 : {
651 : view: destView,
652 : loadOp: 'clear', // Clear attachment before drawing
653 : clearValue: { r: 0, g: 0, b: 0, a: 0 },
654 : storeOp: 'store'
655 : }
656 : ]
657 : })
658 0 : pass.setPipeline(this.blitPipeline)
659 0 : pass.setBindGroup(0, this.backgroundBindGroup)
660 0 : pass.draw(3)
661 0 : pass.end()
662 : } else {
663 : // Clear the destination texture
664 : const clearPass = encoder.beginRenderPass({
665 : colorAttachments: [
666 : {
667 : view: destView,
668 : loadOp: 'clear',
669 : clearValue: { r: 0, g: 0, b: 0, a: 0 },
670 : storeOp: 'store'
671 : }
672 : ]
673 : })
674 0 : clearPass.end()
675 : }
676 :
677 : // Draw the accumulated stroke
678 0 : if (this.currentStrokeTexture) {
679 : // Update uniforms for the preview pass
680 0 : const buffer = new ArrayBuffer(UNIFORM_SIZE)
681 0 : const f32 = new Float32Array(buffer)
682 0 : const u32 = new Uint32Array(buffer)
683 :
684 0 : f32[0] = settings.color[0]
685 0 : f32[1] = settings.color[1]
686 0 : f32[2] = settings.color[2]
687 0 : f32[3] = settings.opacity
688 0 : f32[4] = settings.hardness
689 0 : f32[5] = 0 // Padding
690 0 : f32[6] = settings.screenSize[0]
691 0 : f32[7] = settings.screenSize[1]
692 0 : u32[8] = settings.brushShape
693 0 : this.device.queue.writeBuffer(this.uniformBuffer, 0, buffer)
694 :
695 : // Select preview pipeline based on operation
696 0 : const pipeline = settings.isErasing
697 : ? this.erasePipelinePreview
698 : : this.compositePipelinePreview
699 :
700 : // 1. Texture Bind Group (Group 0)
701 0 : if (!this.previewTextureBindGroup) {
702 0 : this.previewTextureBindGroup = this.device.createBindGroup({
703 : layout: this.textureBindGroupLayout,
704 : entries: [
705 : { binding: 0, resource: this.currentStrokeTexture.createView() }
706 : ]
707 : })
708 : }
709 :
710 : // 2. Uniform Bind Group (Group 1) - Use shared mainUniformBindGroup
711 :
712 0 : const passStroke = encoder.beginRenderPass({
713 : colorAttachments: [
714 : {
715 : view: destView,
716 : loadOp: 'load', // Load the previous pass result
717 : storeOp: 'store'
718 : }
719 : ]
720 : })
721 0 : passStroke.setPipeline(pipeline)
722 0 : passStroke.setBindGroup(0, this.previewTextureBindGroup)
723 0 : passStroke.setBindGroup(1, this.mainUniformBindGroup)
724 0 : passStroke.draw(3)
725 0 : passStroke.end()
726 : }
727 :
728 0 : this.device.queue.submit([encoder.finish()])
729 : }
730 :
731 : // Clear the preview canvas
732 : public clearPreview(destinationCtx: GPUCanvasContext) {
733 0 : const encoder = this.device.createCommandEncoder()
734 : const pass = encoder.beginRenderPass({
735 : colorAttachments: [
736 : {
737 : view: destinationCtx.getCurrentTexture().createView(),
738 : loadOp: 'clear',
739 : clearValue: { r: 0, g: 0, b: 0, a: 0 },
740 : storeOp: 'store'
741 : }
742 : ]
743 : })
744 0 : pass.end()
745 0 : this.device.queue.submit([encoder.finish()])
746 : }
747 :
748 : public prepareReadback(texture: GPUTexture, outputBuffer: GPUBuffer) {
749 0 : if (
750 : this.lastReadbackTexture !== texture ||
751 : this.lastReadbackBuffer !== outputBuffer ||
752 : !this.readbackBindGroup
753 : ) {
754 0 : this.readbackBindGroup = this.device.createBindGroup({
755 : layout: this.readbackPipeline.getBindGroupLayout(0),
756 : entries: [
757 : { binding: 0, resource: texture.createView() },
758 : { binding: 1, resource: { buffer: outputBuffer } }
759 : ]
760 : })
761 0 : this.lastReadbackTexture = texture
762 0 : this.lastReadbackBuffer = outputBuffer
763 : }
764 :
765 0 : const encoder = this.device.createCommandEncoder()
766 0 : const pass = encoder.beginComputePass()
767 0 : pass.setPipeline(this.readbackPipeline)
768 0 : pass.setBindGroup(0, this.readbackBindGroup)
769 :
770 0 : const width = texture.width
771 0 : const height = texture.height
772 : // Dispatch workgroups based on texture dimensions (8x8 block size)
773 0 : pass.dispatchWorkgroups(Math.ceil(width / 8), Math.ceil(height / 8))
774 0 : pass.end()
775 :
776 0 : this.device.queue.submit([encoder.finish()])
777 : }
778 :
779 : public destroy() {
780 0 : this.quadVertexBuffer.destroy()
781 0 : this.indexBuffer.destroy()
782 0 : this.instanceBuffer.destroy()
783 0 : this.uniformBuffer.destroy()
784 0 : if (this.currentStrokeTexture) this.currentStrokeTexture.destroy()
785 :
786 : // Clear cached bind groups
787 0 : this.compositeTextureBindGroup = null
788 0 : this.previewTextureBindGroup = null
789 0 : this.readbackBindGroup = null
790 0 : this.backgroundBindGroup = null
791 0 : this.lastReadbackTexture = null
792 0 : this.lastReadbackBuffer = null
793 0 : this.lastBackgroundTexture = null
794 : }
795 : }
|