@motion-core/motion-gpu 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +325 -0
  3. package/dist/FragCanvas.svelte +511 -0
  4. package/dist/FragCanvas.svelte.d.ts +26 -0
  5. package/dist/MotionGPUErrorOverlay.svelte +394 -0
  6. package/dist/MotionGPUErrorOverlay.svelte.d.ts +7 -0
  7. package/dist/Portal.svelte +46 -0
  8. package/dist/Portal.svelte.d.ts +8 -0
  9. package/dist/advanced-scheduler.d.ts +44 -0
  10. package/dist/advanced-scheduler.js +58 -0
  11. package/dist/advanced.d.ts +14 -0
  12. package/dist/advanced.js +9 -0
  13. package/dist/core/error-diagnostics.d.ts +40 -0
  14. package/dist/core/error-diagnostics.js +111 -0
  15. package/dist/core/error-report.d.ts +67 -0
  16. package/dist/core/error-report.js +190 -0
  17. package/dist/core/material-preprocess.d.ts +63 -0
  18. package/dist/core/material-preprocess.js +166 -0
  19. package/dist/core/material.d.ts +157 -0
  20. package/dist/core/material.js +358 -0
  21. package/dist/core/recompile-policy.d.ts +27 -0
  22. package/dist/core/recompile-policy.js +15 -0
  23. package/dist/core/render-graph.d.ts +55 -0
  24. package/dist/core/render-graph.js +73 -0
  25. package/dist/core/render-targets.d.ts +39 -0
  26. package/dist/core/render-targets.js +63 -0
  27. package/dist/core/renderer.d.ts +9 -0
  28. package/dist/core/renderer.js +1097 -0
  29. package/dist/core/shader.d.ts +42 -0
  30. package/dist/core/shader.js +196 -0
  31. package/dist/core/texture-loader.d.ts +129 -0
  32. package/dist/core/texture-loader.js +295 -0
  33. package/dist/core/textures.d.ts +114 -0
  34. package/dist/core/textures.js +136 -0
  35. package/dist/core/types.d.ts +523 -0
  36. package/dist/core/types.js +4 -0
  37. package/dist/core/uniforms.d.ts +48 -0
  38. package/dist/core/uniforms.js +222 -0
  39. package/dist/current-writable.d.ts +31 -0
  40. package/dist/current-writable.js +27 -0
  41. package/dist/frame-context.d.ts +287 -0
  42. package/dist/frame-context.js +731 -0
  43. package/dist/index.d.ts +17 -0
  44. package/dist/index.js +11 -0
  45. package/dist/motiongpu-context.d.ts +77 -0
  46. package/dist/motiongpu-context.js +26 -0
  47. package/dist/passes/BlitPass.d.ts +32 -0
  48. package/dist/passes/BlitPass.js +158 -0
  49. package/dist/passes/CopyPass.d.ts +25 -0
  50. package/dist/passes/CopyPass.js +53 -0
  51. package/dist/passes/ShaderPass.d.ts +40 -0
  52. package/dist/passes/ShaderPass.js +182 -0
  53. package/dist/passes/index.d.ts +3 -0
  54. package/dist/passes/index.js +3 -0
  55. package/dist/use-motiongpu-user-context.d.ts +35 -0
  56. package/dist/use-motiongpu-user-context.js +74 -0
  57. package/dist/use-texture.d.ts +35 -0
  58. package/dist/use-texture.js +147 -0
  59. package/package.json +94 -0
@@ -0,0 +1,1097 @@
1
+ import { buildRenderTargetSignature, resolveRenderTargetDefinitions } from './render-targets';
2
+ import { planRenderGraph } from './render-graph';
3
+ import { buildShaderSourceWithMap, formatShaderSourceLocation } from './shader';
4
+ import { attachShaderCompilationDiagnostics } from './error-diagnostics';
5
+ import { getTextureMipLevelCount, normalizeTextureDefinitions, resolveTextureUpdateMode, resolveTextureSize, toTextureData } from './textures';
6
+ import { packUniformsInto } from './uniforms';
7
+ /**
8
+ * Binding index for frame uniforms (`time`, `delta`, `resolution`).
9
+ */
10
+ const FRAME_BINDING = 0;
11
+ /**
12
+ * Binding index for material uniform buffer.
13
+ */
14
+ const UNIFORM_BINDING = 1;
15
+ /**
16
+ * First binding index used for texture sampler/texture pairs.
17
+ */
18
+ const FIRST_TEXTURE_BINDING = 2;
19
+ /**
20
+ * Returns sampler/texture binding slots for a texture index.
21
+ */
22
+ function getTextureBindings(index) {
23
+ const samplerBinding = FIRST_TEXTURE_BINDING + index * 2;
24
+ return {
25
+ samplerBinding,
26
+ textureBinding: samplerBinding + 1
27
+ };
28
+ }
29
+ /**
30
+ * Resizes canvas backing store to match client size and DPR.
31
+ */
32
+ function resizeCanvas(canvas, dprInput, cssSize) {
33
+ const dpr = Number.isFinite(dprInput) && dprInput > 0 ? dprInput : 1;
34
+ const rect = cssSize ? null : canvas.getBoundingClientRect();
35
+ const cssWidth = Math.max(0, cssSize?.width ?? rect?.width ?? 0);
36
+ const cssHeight = Math.max(0, cssSize?.height ?? rect?.height ?? 0);
37
+ const width = Math.max(1, Math.floor((cssWidth || 1) * dpr));
38
+ const height = Math.max(1, Math.floor((cssHeight || 1) * dpr));
39
+ if (canvas.width !== width || canvas.height !== height) {
40
+ canvas.width = width;
41
+ canvas.height = height;
42
+ }
43
+ return { width, height };
44
+ }
45
+ /**
46
+ * Throws when a shader module contains WGSL compilation errors.
47
+ */
48
+ async function assertCompilation(module, options) {
49
+ const info = await module.getCompilationInfo();
50
+ const errors = info.messages.filter((message) => message.type === 'error');
51
+ if (errors.length === 0) {
52
+ return;
53
+ }
54
+ const diagnostics = errors.map((message) => ({
55
+ generatedLine: message.lineNum,
56
+ message: message.message,
57
+ linePos: message.linePos,
58
+ lineLength: message.length,
59
+ sourceLocation: options?.lineMap?.[message.lineNum] ?? null
60
+ }));
61
+ const summary = diagnostics
62
+ .map((diagnostic) => {
63
+ const sourceLabel = formatShaderSourceLocation(diagnostic.sourceLocation);
64
+ const generatedLineLabel = diagnostic.generatedLine > 0 ? `generated WGSL line ${diagnostic.generatedLine}` : null;
65
+ const contextLabel = [sourceLabel, generatedLineLabel].filter((value) => Boolean(value));
66
+ if (contextLabel.length === 0) {
67
+ return diagnostic.message;
68
+ }
69
+ return `[${contextLabel.join(' | ')}] ${diagnostic.message}`;
70
+ })
71
+ .join('\n');
72
+ const error = new Error(`WGSL compilation failed:\n${summary}`);
73
+ throw attachShaderCompilationDiagnostics(error, {
74
+ kind: 'shader-compilation',
75
+ diagnostics,
76
+ fragmentSource: options?.fragmentSource ?? '',
77
+ includeSources: options?.includeSources ?? {},
78
+ ...(options?.defineBlockSource !== undefined
79
+ ? { defineBlockSource: options.defineBlockSource }
80
+ : {}),
81
+ materialSource: options?.materialSource ?? null
82
+ });
83
+ }
84
+ /**
85
+ * Creates a 1x1 white fallback texture used before user textures become available.
86
+ */
87
+ function createFallbackTexture(device, format) {
88
+ const texture = device.createTexture({
89
+ size: { width: 1, height: 1, depthOrArrayLayers: 1 },
90
+ format,
91
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
92
+ });
93
+ const pixel = new Uint8Array([255, 255, 255, 255]);
94
+ device.queue.writeTexture({ texture }, pixel, { offset: 0, bytesPerRow: 4, rowsPerImage: 1 }, { width: 1, height: 1, depthOrArrayLayers: 1 });
95
+ return texture;
96
+ }
97
+ /**
98
+ * Creates an offscreen canvas used for CPU mipmap generation.
99
+ */
100
+ function createMipmapCanvas(width, height) {
101
+ if (typeof OffscreenCanvas !== 'undefined') {
102
+ return new OffscreenCanvas(width, height);
103
+ }
104
+ const canvas = document.createElement('canvas');
105
+ canvas.width = width;
106
+ canvas.height = height;
107
+ return canvas;
108
+ }
109
+ /**
110
+ * Creates typed descriptor for `copyExternalImageToTexture`.
111
+ */
112
+ function createExternalCopySource(source, options) {
113
+ const descriptor = {
114
+ source,
115
+ ...(options.flipY ? { flipY: true } : {}),
116
+ ...(options.premultipliedAlpha ? { premultipliedAlpha: true } : {})
117
+ };
118
+ return descriptor;
119
+ }
120
+ /**
121
+ * Uploads source content to a GPU texture and optionally generates mip chain on CPU.
122
+ */
123
+ function uploadTexture(device, texture, binding, source, width, height, mipLevelCount) {
124
+ device.queue.copyExternalImageToTexture(createExternalCopySource(source, {
125
+ flipY: binding.flipY,
126
+ premultipliedAlpha: binding.premultipliedAlpha
127
+ }), { texture, mipLevel: 0 }, { width, height, depthOrArrayLayers: 1 });
128
+ if (!binding.generateMipmaps || mipLevelCount <= 1) {
129
+ return;
130
+ }
131
+ let previousSource = source;
132
+ let previousWidth = width;
133
+ let previousHeight = height;
134
+ for (let level = 1; level < mipLevelCount; level += 1) {
135
+ const nextWidth = Math.max(1, Math.floor(previousWidth / 2));
136
+ const nextHeight = Math.max(1, Math.floor(previousHeight / 2));
137
+ const canvas = createMipmapCanvas(nextWidth, nextHeight);
138
+ const context = canvas.getContext('2d');
139
+ if (!context) {
140
+ throw new Error('Unable to create 2D context for mipmap generation');
141
+ }
142
+ context.drawImage(previousSource, 0, 0, previousWidth, previousHeight, 0, 0, nextWidth, nextHeight);
143
+ device.queue.copyExternalImageToTexture(createExternalCopySource(canvas, {
144
+ premultipliedAlpha: binding.premultipliedAlpha
145
+ }), { texture, mipLevel: level }, { width: nextWidth, height: nextHeight, depthOrArrayLayers: 1 });
146
+ previousSource = canvas;
147
+ previousWidth = nextWidth;
148
+ previousHeight = nextHeight;
149
+ }
150
+ }
151
+ /**
152
+ * Creates bind group layout entries for frame/uniform buffers plus texture bindings.
153
+ */
154
+ function createBindGroupLayoutEntries(textureBindings) {
155
+ const entries = [
156
+ {
157
+ binding: FRAME_BINDING,
158
+ visibility: GPUShaderStage.FRAGMENT,
159
+ buffer: { type: 'uniform', minBindingSize: 16 }
160
+ },
161
+ {
162
+ binding: UNIFORM_BINDING,
163
+ visibility: GPUShaderStage.FRAGMENT,
164
+ buffer: { type: 'uniform' }
165
+ }
166
+ ];
167
+ for (const binding of textureBindings) {
168
+ entries.push({
169
+ binding: binding.samplerBinding,
170
+ visibility: GPUShaderStage.FRAGMENT,
171
+ sampler: { type: 'filtering' }
172
+ });
173
+ entries.push({
174
+ binding: binding.textureBinding,
175
+ visibility: GPUShaderStage.FRAGMENT,
176
+ texture: {
177
+ sampleType: 'float',
178
+ viewDimension: '2d',
179
+ multisampled: false
180
+ }
181
+ });
182
+ }
183
+ return entries;
184
+ }
185
+ /**
186
+ * Computes dirty float ranges between two uniform snapshots.
187
+ */
188
+ function findDirtyFloatRanges(previous, next) {
189
+ const ranges = [];
190
+ let start = -1;
191
+ for (let index = 0; index < next.length; index += 1) {
192
+ if (previous[index] !== next[index]) {
193
+ if (start === -1) {
194
+ start = index;
195
+ }
196
+ continue;
197
+ }
198
+ if (start !== -1) {
199
+ ranges.push({ start, count: index - start });
200
+ start = -1;
201
+ }
202
+ }
203
+ if (start !== -1) {
204
+ ranges.push({ start, count: next.length - start });
205
+ }
206
+ return ranges;
207
+ }
208
+ /**
209
+ * Determines whether shader output should perform linear-to-sRGB conversion.
210
+ */
211
+ function shouldConvertLinearToSrgb(outputColorSpace, canvasFormat) {
212
+ if (outputColorSpace !== 'srgb') {
213
+ return false;
214
+ }
215
+ return !canvasFormat.endsWith('-srgb');
216
+ }
217
+ /**
218
+ * WGSL shader used to blit an offscreen texture to the canvas.
219
+ */
220
+ function createFullscreenBlitShader() {
221
+ return `
222
+ struct MotionGPUVertexOut {
223
+ @builtin(position) position: vec4f,
224
+ @location(0) uv: vec2f,
225
+ };
226
+
227
+ @group(0) @binding(0) var motiongpuBlitSampler: sampler;
228
+ @group(0) @binding(1) var motiongpuBlitTexture: texture_2d<f32>;
229
+
230
+ @vertex
231
+ fn motiongpuBlitVertex(@builtin(vertex_index) index: u32) -> MotionGPUVertexOut {
232
+ var positions = array<vec2f, 3>(
233
+ vec2f(-1.0, -3.0),
234
+ vec2f(-1.0, 1.0),
235
+ vec2f(3.0, 1.0)
236
+ );
237
+
238
+ let position = positions[index];
239
+ var out: MotionGPUVertexOut;
240
+ out.position = vec4f(position, 0.0, 1.0);
241
+ out.uv = (position + vec2f(1.0, 1.0)) * 0.5;
242
+ return out;
243
+ }
244
+
245
+ @fragment
246
+ fn motiongpuBlitFragment(in: MotionGPUVertexOut) -> @location(0) vec4f {
247
+ return textureSample(motiongpuBlitTexture, motiongpuBlitSampler, in.uv);
248
+ }
249
+ `;
250
+ }
251
+ /**
252
+ * Allocates a render target texture with usage flags suitable for passes/blits.
253
+ */
254
+ function createRenderTexture(device, width, height, format) {
255
+ const texture = device.createTexture({
256
+ size: { width, height, depthOrArrayLayers: 1 },
257
+ format,
258
+ usage: GPUTextureUsage.TEXTURE_BINDING |
259
+ GPUTextureUsage.RENDER_ATTACHMENT |
260
+ GPUTextureUsage.COPY_DST |
261
+ GPUTextureUsage.COPY_SRC
262
+ });
263
+ return {
264
+ texture,
265
+ view: texture.createView(),
266
+ width,
267
+ height,
268
+ format
269
+ };
270
+ }
271
+ /**
272
+ * Destroys a render target texture if present.
273
+ */
274
+ function destroyRenderTexture(target) {
275
+ target?.texture.destroy();
276
+ }
277
+ /**
278
+ * Creates the WebGPU renderer used by `FragCanvas`.
279
+ *
280
+ * @param options - Renderer creation options resolved from material/context state.
281
+ * @returns Renderer instance with `render` and `destroy`.
282
+ * @throws {Error} On WebGPU unavailability, shader compilation issues, or runtime setup failures.
283
+ */
284
+ export async function createRenderer(options) {
285
+ if (!navigator.gpu) {
286
+ throw new Error('WebGPU is not available in this browser');
287
+ }
288
+ const context = options.canvas.getContext('webgpu');
289
+ if (!context) {
290
+ throw new Error('Canvas does not support webgpu context');
291
+ }
292
+ const format = navigator.gpu.getPreferredCanvasFormat();
293
+ const adapter = await navigator.gpu.requestAdapter(options.adapterOptions);
294
+ if (!adapter) {
295
+ throw new Error('Unable to acquire WebGPU adapter');
296
+ }
297
+ const device = await adapter.requestDevice(options.deviceDescriptor);
298
+ let isDestroyed = false;
299
+ let deviceLostMessage = null;
300
+ let uncapturedErrorMessage = null;
301
+ const initializationCleanups = [];
302
+ let acceptInitializationCleanups = true;
303
+ const registerInitializationCleanup = (cleanup) => {
304
+ if (!acceptInitializationCleanups) {
305
+ return;
306
+ }
307
+ options.__onInitializationCleanupRegistered?.();
308
+ initializationCleanups.push(cleanup);
309
+ };
310
+ const runInitializationCleanups = () => {
311
+ for (let index = initializationCleanups.length - 1; index >= 0; index -= 1) {
312
+ try {
313
+ initializationCleanups[index]?.();
314
+ }
315
+ catch {
316
+ // Best-effort cleanup on failed renderer initialization.
317
+ }
318
+ }
319
+ initializationCleanups.length = 0;
320
+ };
321
+ void device.lost.then((info) => {
322
+ if (isDestroyed) {
323
+ return;
324
+ }
325
+ const reason = info.reason ? ` (${info.reason})` : '';
326
+ const details = info.message?.trim();
327
+ deviceLostMessage = details
328
+ ? `WebGPU device lost: ${details}${reason}`
329
+ : `WebGPU device lost${reason}`;
330
+ });
331
+ const handleUncapturedError = (event) => {
332
+ if (isDestroyed) {
333
+ return;
334
+ }
335
+ const message = event.error instanceof Error
336
+ ? event.error.message
337
+ : String(event.error?.message ?? event.error);
338
+ uncapturedErrorMessage = `WebGPU uncaptured error: ${message}`;
339
+ };
340
+ device.addEventListener('uncapturederror', handleUncapturedError);
341
+ try {
342
+ const convertLinearToSrgb = shouldConvertLinearToSrgb(options.outputColorSpace, format);
343
+ const builtShader = buildShaderSourceWithMap(options.fragmentWgsl, options.uniformLayout, options.textureKeys, {
344
+ convertLinearToSrgb,
345
+ fragmentLineMap: options.fragmentLineMap
346
+ });
347
+ const shaderModule = device.createShaderModule({ code: builtShader.code });
348
+ await assertCompilation(shaderModule, {
349
+ lineMap: builtShader.lineMap,
350
+ fragmentSource: options.fragmentSource,
351
+ includeSources: options.includeSources,
352
+ ...(options.defineBlockSource !== undefined
353
+ ? { defineBlockSource: options.defineBlockSource }
354
+ : {}),
355
+ materialSource: options.materialSource ?? null
356
+ });
357
+ const normalizedTextureDefinitions = normalizeTextureDefinitions(options.textureDefinitions, options.textureKeys);
358
+ const textureBindings = options.textureKeys.map((key, index) => {
359
+ const config = normalizedTextureDefinitions[key];
360
+ if (!config) {
361
+ throw new Error(`Missing texture definition for "${key}"`);
362
+ }
363
+ const { samplerBinding, textureBinding } = getTextureBindings(index);
364
+ const sampler = device.createSampler({
365
+ magFilter: config.filter,
366
+ minFilter: config.filter,
367
+ mipmapFilter: config.generateMipmaps ? config.filter : 'nearest',
368
+ addressModeU: config.addressModeU,
369
+ addressModeV: config.addressModeV,
370
+ maxAnisotropy: config.filter === 'linear' ? config.anisotropy : 1
371
+ });
372
+ const fallbackTexture = createFallbackTexture(device, config.format);
373
+ registerInitializationCleanup(() => {
374
+ fallbackTexture.destroy();
375
+ });
376
+ const fallbackView = fallbackTexture.createView();
377
+ const runtimeBinding = {
378
+ key,
379
+ samplerBinding,
380
+ textureBinding,
381
+ sampler,
382
+ fallbackTexture,
383
+ fallbackView,
384
+ texture: null,
385
+ view: fallbackView,
386
+ source: null,
387
+ width: undefined,
388
+ height: undefined,
389
+ mipLevelCount: 1,
390
+ format: config.format,
391
+ colorSpace: config.colorSpace,
392
+ defaultColorSpace: config.colorSpace,
393
+ flipY: config.flipY,
394
+ defaultFlipY: config.flipY,
395
+ generateMipmaps: config.generateMipmaps,
396
+ defaultGenerateMipmaps: config.generateMipmaps,
397
+ premultipliedAlpha: config.premultipliedAlpha,
398
+ defaultPremultipliedAlpha: config.premultipliedAlpha,
399
+ update: config.update ?? 'once',
400
+ lastToken: null
401
+ };
402
+ if (config.update !== undefined) {
403
+ runtimeBinding.defaultUpdate = config.update;
404
+ }
405
+ return runtimeBinding;
406
+ });
407
+ const bindGroupLayout = device.createBindGroupLayout({
408
+ entries: createBindGroupLayoutEntries(textureBindings)
409
+ });
410
+ const pipelineLayout = device.createPipelineLayout({
411
+ bindGroupLayouts: [bindGroupLayout]
412
+ });
413
+ const pipeline = device.createRenderPipeline({
414
+ layout: pipelineLayout,
415
+ vertex: {
416
+ module: shaderModule,
417
+ entryPoint: 'motiongpuVertex'
418
+ },
419
+ fragment: {
420
+ module: shaderModule,
421
+ entryPoint: 'motiongpuFragment',
422
+ targets: [{ format }]
423
+ },
424
+ primitive: {
425
+ topology: 'triangle-list'
426
+ }
427
+ });
428
+ const blitShaderModule = device.createShaderModule({
429
+ code: createFullscreenBlitShader()
430
+ });
431
+ await assertCompilation(blitShaderModule);
432
+ const blitBindGroupLayout = device.createBindGroupLayout({
433
+ entries: [
434
+ {
435
+ binding: 0,
436
+ visibility: GPUShaderStage.FRAGMENT,
437
+ sampler: { type: 'filtering' }
438
+ },
439
+ {
440
+ binding: 1,
441
+ visibility: GPUShaderStage.FRAGMENT,
442
+ texture: {
443
+ sampleType: 'float',
444
+ viewDimension: '2d',
445
+ multisampled: false
446
+ }
447
+ }
448
+ ]
449
+ });
450
+ const blitPipelineLayout = device.createPipelineLayout({
451
+ bindGroupLayouts: [blitBindGroupLayout]
452
+ });
453
+ const blitPipeline = device.createRenderPipeline({
454
+ layout: blitPipelineLayout,
455
+ vertex: { module: blitShaderModule, entryPoint: 'motiongpuBlitVertex' },
456
+ fragment: {
457
+ module: blitShaderModule,
458
+ entryPoint: 'motiongpuBlitFragment',
459
+ targets: [{ format }]
460
+ },
461
+ primitive: {
462
+ topology: 'triangle-list'
463
+ }
464
+ });
465
+ const blitSampler = device.createSampler({
466
+ magFilter: 'linear',
467
+ minFilter: 'linear',
468
+ addressModeU: 'clamp-to-edge',
469
+ addressModeV: 'clamp-to-edge'
470
+ });
471
+ let blitBindGroupByView = new WeakMap();
472
+ const frameBuffer = device.createBuffer({
473
+ size: 16,
474
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
475
+ });
476
+ registerInitializationCleanup(() => {
477
+ frameBuffer.destroy();
478
+ });
479
+ const uniformBuffer = device.createBuffer({
480
+ size: options.uniformLayout.byteLength,
481
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
482
+ });
483
+ registerInitializationCleanup(() => {
484
+ uniformBuffer.destroy();
485
+ });
486
+ const frameScratch = new Float32Array(4);
487
+ const uniformScratch = new Float32Array(options.uniformLayout.byteLength / 4);
488
+ const uniformPrevious = new Float32Array(options.uniformLayout.byteLength / 4);
489
+ let hasUniformSnapshot = false;
490
+ /**
491
+ * Rebuilds bind group using current texture views.
492
+ */
493
+ const createBindGroup = () => {
494
+ const entries = [
495
+ { binding: FRAME_BINDING, resource: { buffer: frameBuffer } },
496
+ { binding: UNIFORM_BINDING, resource: { buffer: uniformBuffer } }
497
+ ];
498
+ for (const binding of textureBindings) {
499
+ entries.push({
500
+ binding: binding.samplerBinding,
501
+ resource: binding.sampler
502
+ });
503
+ entries.push({
504
+ binding: binding.textureBinding,
505
+ resource: binding.view
506
+ });
507
+ }
508
+ return device.createBindGroup({
509
+ layout: bindGroupLayout,
510
+ entries
511
+ });
512
+ };
513
+ /**
514
+ * Synchronizes one runtime texture binding with incoming texture value.
515
+ *
516
+ * @returns `true` when bind group must be rebuilt.
517
+ */
518
+ const updateTextureBinding = (binding, value, renderMode) => {
519
+ const nextData = toTextureData(value);
520
+ if (!nextData) {
521
+ if (binding.source === null && binding.texture === null) {
522
+ return false;
523
+ }
524
+ binding.texture?.destroy();
525
+ binding.texture = null;
526
+ binding.view = binding.fallbackView;
527
+ binding.source = null;
528
+ binding.width = undefined;
529
+ binding.height = undefined;
530
+ binding.lastToken = null;
531
+ return true;
532
+ }
533
+ const source = nextData.source;
534
+ const colorSpace = nextData.colorSpace ?? binding.defaultColorSpace;
535
+ const format = colorSpace === 'linear' ? 'rgba8unorm' : 'rgba8unorm-srgb';
536
+ const flipY = nextData.flipY ?? binding.defaultFlipY;
537
+ const premultipliedAlpha = nextData.premultipliedAlpha ?? binding.defaultPremultipliedAlpha;
538
+ const generateMipmaps = nextData.generateMipmaps ?? binding.defaultGenerateMipmaps;
539
+ const update = resolveTextureUpdateMode({
540
+ source,
541
+ ...(nextData.update !== undefined ? { override: nextData.update } : {}),
542
+ ...(binding.defaultUpdate !== undefined ? { defaultMode: binding.defaultUpdate } : {})
543
+ });
544
+ const { width, height } = resolveTextureSize(nextData);
545
+ const mipLevelCount = generateMipmaps ? getTextureMipLevelCount(width, height) : 1;
546
+ const sourceChanged = binding.source !== source;
547
+ const tokenChanged = binding.lastToken !== value;
548
+ const requiresReallocation = binding.texture === null ||
549
+ binding.width !== width ||
550
+ binding.height !== height ||
551
+ binding.mipLevelCount !== mipLevelCount ||
552
+ binding.format !== format;
553
+ if (!requiresReallocation) {
554
+ const shouldUpload = sourceChanged ||
555
+ update === 'perFrame' ||
556
+ (update === 'onInvalidate' && (renderMode !== 'always' || tokenChanged));
557
+ if (shouldUpload && binding.texture) {
558
+ binding.flipY = flipY;
559
+ binding.generateMipmaps = generateMipmaps;
560
+ binding.premultipliedAlpha = premultipliedAlpha;
561
+ binding.colorSpace = colorSpace;
562
+ uploadTexture(device, binding.texture, binding, source, width, height, mipLevelCount);
563
+ }
564
+ binding.source = source;
565
+ binding.width = width;
566
+ binding.height = height;
567
+ binding.mipLevelCount = mipLevelCount;
568
+ binding.update = update;
569
+ binding.lastToken = value;
570
+ return false;
571
+ }
572
+ const texture = device.createTexture({
573
+ size: { width, height, depthOrArrayLayers: 1 },
574
+ format,
575
+ mipLevelCount,
576
+ usage: GPUTextureUsage.TEXTURE_BINDING |
577
+ GPUTextureUsage.COPY_DST |
578
+ GPUTextureUsage.RENDER_ATTACHMENT
579
+ });
580
+ registerInitializationCleanup(() => {
581
+ texture.destroy();
582
+ });
583
+ binding.flipY = flipY;
584
+ binding.generateMipmaps = generateMipmaps;
585
+ binding.premultipliedAlpha = premultipliedAlpha;
586
+ binding.colorSpace = colorSpace;
587
+ binding.format = format;
588
+ uploadTexture(device, texture, binding, source, width, height, mipLevelCount);
589
+ binding.texture?.destroy();
590
+ binding.texture = texture;
591
+ binding.view = texture.createView();
592
+ binding.source = source;
593
+ binding.width = width;
594
+ binding.height = height;
595
+ binding.mipLevelCount = mipLevelCount;
596
+ binding.update = update;
597
+ binding.lastToken = value;
598
+ return true;
599
+ };
600
+ for (const binding of textureBindings) {
601
+ const defaultSource = normalizedTextureDefinitions[binding.key]?.source ?? null;
602
+ updateTextureBinding(binding, defaultSource, 'always');
603
+ }
604
+ let bindGroup = createBindGroup();
605
+ let sourceSlotTarget = null;
606
+ let targetSlotTarget = null;
607
+ let renderTargetSignature = '';
608
+ let renderTargetSnapshot = {};
609
+ let renderTargetKeys = [];
610
+ let cachedGraphPlan = null;
611
+ let cachedGraphRenderTargetSignature = '';
612
+ const cachedGraphClearColor = [NaN, NaN, NaN, NaN];
613
+ const cachedGraphPasses = [];
614
+ let contextConfigured = false;
615
+ let configuredWidth = 0;
616
+ let configuredHeight = 0;
617
+ const runtimeRenderTargets = new Map();
618
+ const activePasses = [];
619
+ const lifecyclePreviousSet = new Set();
620
+ const lifecycleNextSet = new Set();
621
+ const lifecycleUniquePasses = [];
622
+ let lifecyclePassesRef = null;
623
+ let passWidth = 0;
624
+ let passHeight = 0;
625
+ /**
626
+ * Resolves active render pass list for current frame.
627
+ */
628
+ const resolvePasses = () => {
629
+ return options.getPasses?.() ?? options.passes ?? [];
630
+ };
631
+ /**
632
+ * Resolves active render target declarations for current frame.
633
+ */
634
+ const resolveRenderTargets = () => {
635
+ return options.getRenderTargets?.() ?? options.renderTargets;
636
+ };
637
+ /**
638
+ * Checks whether cached render-graph plan can be reused for this frame.
639
+ */
640
+ const isGraphPlanCacheValid = (passes, clearColor) => {
641
+ if (!cachedGraphPlan) {
642
+ return false;
643
+ }
644
+ if (cachedGraphRenderTargetSignature !== renderTargetSignature) {
645
+ return false;
646
+ }
647
+ if (cachedGraphClearColor[0] !== clearColor[0] ||
648
+ cachedGraphClearColor[1] !== clearColor[1] ||
649
+ cachedGraphClearColor[2] !== clearColor[2] ||
650
+ cachedGraphClearColor[3] !== clearColor[3]) {
651
+ return false;
652
+ }
653
+ if (cachedGraphPasses.length !== passes.length) {
654
+ return false;
655
+ }
656
+ for (let index = 0; index < passes.length; index += 1) {
657
+ const pass = passes[index];
658
+ const snapshot = cachedGraphPasses[index];
659
+ if (!pass || !snapshot || snapshot.pass !== pass) {
660
+ return false;
661
+ }
662
+ if (snapshot.enabled !== pass.enabled ||
663
+ snapshot.needsSwap !== pass.needsSwap ||
664
+ snapshot.input !== pass.input ||
665
+ snapshot.output !== pass.output ||
666
+ snapshot.clear !== pass.clear ||
667
+ snapshot.preserve !== pass.preserve) {
668
+ return false;
669
+ }
670
+ const passClearColor = pass.clearColor;
671
+ const hasPassClearColor = passClearColor !== undefined;
672
+ if (snapshot.hasClearColor !== hasPassClearColor) {
673
+ return false;
674
+ }
675
+ if (passClearColor) {
676
+ if (snapshot.clearColor0 !== passClearColor[0] ||
677
+ snapshot.clearColor1 !== passClearColor[1] ||
678
+ snapshot.clearColor2 !== passClearColor[2] ||
679
+ snapshot.clearColor3 !== passClearColor[3]) {
680
+ return false;
681
+ }
682
+ }
683
+ }
684
+ return true;
685
+ };
686
+ /**
687
+ * Updates render-graph cache with current pass set.
688
+ */
689
+ const updateGraphPlanCache = (passes, clearColor, graphPlan) => {
690
+ cachedGraphPlan = graphPlan;
691
+ cachedGraphRenderTargetSignature = renderTargetSignature;
692
+ cachedGraphClearColor[0] = clearColor[0];
693
+ cachedGraphClearColor[1] = clearColor[1];
694
+ cachedGraphClearColor[2] = clearColor[2];
695
+ cachedGraphClearColor[3] = clearColor[3];
696
+ cachedGraphPasses.length = passes.length;
697
+ let index = 0;
698
+ for (const pass of passes) {
699
+ const passClearColor = pass.clearColor;
700
+ const hasPassClearColor = passClearColor !== undefined;
701
+ const snapshot = cachedGraphPasses[index];
702
+ if (!snapshot) {
703
+ cachedGraphPasses[index] = {
704
+ pass,
705
+ enabled: pass.enabled,
706
+ needsSwap: pass.needsSwap,
707
+ input: pass.input,
708
+ output: pass.output,
709
+ clear: pass.clear,
710
+ preserve: pass.preserve,
711
+ hasClearColor: hasPassClearColor,
712
+ clearColor0: passClearColor?.[0] ?? 0,
713
+ clearColor1: passClearColor?.[1] ?? 0,
714
+ clearColor2: passClearColor?.[2] ?? 0,
715
+ clearColor3: passClearColor?.[3] ?? 0
716
+ };
717
+ index += 1;
718
+ continue;
719
+ }
720
+ snapshot.pass = pass;
721
+ snapshot.enabled = pass.enabled;
722
+ snapshot.needsSwap = pass.needsSwap;
723
+ snapshot.input = pass.input;
724
+ snapshot.output = pass.output;
725
+ snapshot.clear = pass.clear;
726
+ snapshot.preserve = pass.preserve;
727
+ snapshot.hasClearColor = hasPassClearColor;
728
+ snapshot.clearColor0 = passClearColor?.[0] ?? 0;
729
+ snapshot.clearColor1 = passClearColor?.[1] ?? 0;
730
+ snapshot.clearColor2 = passClearColor?.[2] ?? 0;
731
+ snapshot.clearColor3 = passClearColor?.[3] ?? 0;
732
+ index += 1;
733
+ }
734
+ };
735
+ /**
736
+ * Synchronizes pass lifecycle callbacks and resize notifications.
737
+ */
738
+ const syncPassLifecycle = (passes, width, height) => {
739
+ const resized = passWidth !== width || passHeight !== height;
740
+ if (!resized && lifecyclePassesRef === passes && passes.length === activePasses.length) {
741
+ let isSameOrder = true;
742
+ for (let index = 0; index < passes.length; index += 1) {
743
+ if (activePasses[index] !== passes[index]) {
744
+ isSameOrder = false;
745
+ break;
746
+ }
747
+ }
748
+ if (isSameOrder) {
749
+ return;
750
+ }
751
+ }
752
+ lifecycleNextSet.clear();
753
+ lifecycleUniquePasses.length = 0;
754
+ for (const pass of passes) {
755
+ if (lifecycleNextSet.has(pass)) {
756
+ continue;
757
+ }
758
+ lifecycleNextSet.add(pass);
759
+ lifecycleUniquePasses.push(pass);
760
+ }
761
+ lifecyclePreviousSet.clear();
762
+ for (const pass of activePasses) {
763
+ lifecyclePreviousSet.add(pass);
764
+ }
765
+ for (const pass of activePasses) {
766
+ if (!lifecycleNextSet.has(pass)) {
767
+ pass.dispose?.();
768
+ }
769
+ }
770
+ for (const pass of lifecycleUniquePasses) {
771
+ if (resized || !lifecyclePreviousSet.has(pass)) {
772
+ pass.setSize?.(width, height);
773
+ }
774
+ }
775
+ activePasses.length = 0;
776
+ for (const pass of lifecycleUniquePasses) {
777
+ activePasses.push(pass);
778
+ }
779
+ lifecyclePassesRef = passes;
780
+ passWidth = width;
781
+ passHeight = height;
782
+ };
783
+ /**
784
+ * Ensures internal ping-pong slot texture matches current canvas size/format.
785
+ */
786
+ const ensureSlotTarget = (slot, width, height) => {
787
+ const current = slot === 'source' ? sourceSlotTarget : targetSlotTarget;
788
+ if (current &&
789
+ current.width === width &&
790
+ current.height === height &&
791
+ current.format === format) {
792
+ return current;
793
+ }
794
+ destroyRenderTexture(current);
795
+ const next = createRenderTexture(device, width, height, format);
796
+ if (slot === 'source') {
797
+ sourceSlotTarget = next;
798
+ }
799
+ else {
800
+ targetSlotTarget = next;
801
+ }
802
+ return next;
803
+ };
804
+ /**
805
+ * Creates/updates runtime render targets and returns immutable pass snapshot.
806
+ */
807
+ const syncRenderTargets = (canvasWidth, canvasHeight) => {
808
+ const resolvedDefinitions = resolveRenderTargetDefinitions(resolveRenderTargets(), canvasWidth, canvasHeight, format);
809
+ const nextSignature = buildRenderTargetSignature(resolvedDefinitions);
810
+ if (nextSignature !== renderTargetSignature) {
811
+ const activeKeys = new Set(resolvedDefinitions.map((definition) => definition.key));
812
+ for (const [key, target] of runtimeRenderTargets.entries()) {
813
+ if (!activeKeys.has(key)) {
814
+ target.texture.destroy();
815
+ runtimeRenderTargets.delete(key);
816
+ }
817
+ }
818
+ for (const definition of resolvedDefinitions) {
819
+ const current = runtimeRenderTargets.get(definition.key);
820
+ if (current &&
821
+ current.width === definition.width &&
822
+ current.height === definition.height &&
823
+ current.format === definition.format) {
824
+ continue;
825
+ }
826
+ current?.texture.destroy();
827
+ runtimeRenderTargets.set(definition.key, createRenderTexture(device, definition.width, definition.height, definition.format));
828
+ }
829
+ renderTargetSignature = nextSignature;
830
+ const nextSnapshot = {};
831
+ const nextKeys = [];
832
+ for (const definition of resolvedDefinitions) {
833
+ const target = runtimeRenderTargets.get(definition.key);
834
+ if (!target) {
835
+ continue;
836
+ }
837
+ nextKeys.push(definition.key);
838
+ nextSnapshot[definition.key] = {
839
+ texture: target.texture,
840
+ view: target.view,
841
+ width: target.width,
842
+ height: target.height,
843
+ format: target.format
844
+ };
845
+ }
846
+ renderTargetSnapshot = nextSnapshot;
847
+ renderTargetKeys = nextKeys;
848
+ }
849
+ return renderTargetSnapshot;
850
+ };
851
+ /**
852
+ * Blits a texture view to the current canvas texture.
853
+ */
854
+ const blitToCanvas = (commandEncoder, sourceView, canvasView, clearColor) => {
855
+ let bindGroup = blitBindGroupByView.get(sourceView);
856
+ if (!bindGroup) {
857
+ bindGroup = device.createBindGroup({
858
+ layout: blitBindGroupLayout,
859
+ entries: [
860
+ { binding: 0, resource: blitSampler },
861
+ { binding: 1, resource: sourceView }
862
+ ]
863
+ });
864
+ blitBindGroupByView.set(sourceView, bindGroup);
865
+ }
866
+ const pass = commandEncoder.beginRenderPass({
867
+ colorAttachments: [
868
+ {
869
+ view: canvasView,
870
+ clearValue: {
871
+ r: clearColor[0],
872
+ g: clearColor[1],
873
+ b: clearColor[2],
874
+ a: clearColor[3]
875
+ },
876
+ loadOp: 'clear',
877
+ storeOp: 'store'
878
+ }
879
+ ]
880
+ });
881
+ pass.setPipeline(blitPipeline);
882
+ pass.setBindGroup(0, bindGroup);
883
+ pass.draw(3);
884
+ pass.end();
885
+ };
886
+ /**
887
+ * Executes a full frame render.
888
+ */
889
+ const render = ({ time, delta, renderMode, uniforms, textures, canvasSize }) => {
890
+ if (deviceLostMessage) {
891
+ throw new Error(deviceLostMessage);
892
+ }
893
+ if (uncapturedErrorMessage) {
894
+ const message = uncapturedErrorMessage;
895
+ uncapturedErrorMessage = null;
896
+ throw new Error(message);
897
+ }
898
+ const { width, height } = resizeCanvas(options.canvas, options.getDpr(), canvasSize);
899
+ if (!contextConfigured || configuredWidth !== width || configuredHeight !== height) {
900
+ context.configure({
901
+ device,
902
+ format,
903
+ alphaMode: 'premultiplied'
904
+ });
905
+ contextConfigured = true;
906
+ configuredWidth = width;
907
+ configuredHeight = height;
908
+ }
909
+ frameScratch[0] = time;
910
+ frameScratch[1] = delta;
911
+ frameScratch[2] = width;
912
+ frameScratch[3] = height;
913
+ device.queue.writeBuffer(frameBuffer, 0, frameScratch.buffer, frameScratch.byteOffset, frameScratch.byteLength);
914
+ packUniformsInto(uniforms, options.uniformLayout, uniformScratch);
915
+ if (!hasUniformSnapshot) {
916
+ device.queue.writeBuffer(uniformBuffer, 0, uniformScratch.buffer, uniformScratch.byteOffset, uniformScratch.byteLength);
917
+ uniformPrevious.set(uniformScratch);
918
+ hasUniformSnapshot = true;
919
+ }
920
+ else {
921
+ const dirtyRanges = findDirtyFloatRanges(uniformPrevious, uniformScratch);
922
+ for (const range of dirtyRanges) {
923
+ const byteOffset = range.start * 4;
924
+ const byteLength = range.count * 4;
925
+ device.queue.writeBuffer(uniformBuffer, byteOffset, uniformScratch.buffer, uniformScratch.byteOffset + byteOffset, byteLength);
926
+ }
927
+ if (dirtyRanges.length > 0) {
928
+ uniformPrevious.set(uniformScratch);
929
+ }
930
+ }
931
+ let bindGroupDirty = false;
932
+ for (const binding of textureBindings) {
933
+ const nextTexture = textures[binding.key] ?? normalizedTextureDefinitions[binding.key]?.source ?? null;
934
+ if (updateTextureBinding(binding, nextTexture, renderMode)) {
935
+ bindGroupDirty = true;
936
+ }
937
+ }
938
+ if (bindGroupDirty) {
939
+ bindGroup = createBindGroup();
940
+ }
941
+ const commandEncoder = device.createCommandEncoder();
942
+ const passes = resolvePasses();
943
+ const clearColor = options.getClearColor();
944
+ syncPassLifecycle(passes, width, height);
945
+ const runtimeTargets = syncRenderTargets(width, height);
946
+ const graphPlan = isGraphPlanCacheValid(passes, clearColor)
947
+ ? cachedGraphPlan
948
+ : (() => {
949
+ const nextPlan = planRenderGraph(passes, clearColor, renderTargetKeys);
950
+ updateGraphPlanCache(passes, clearColor, nextPlan);
951
+ return nextPlan;
952
+ })();
953
+ const canvasTexture = context.getCurrentTexture();
954
+ const canvasSurface = {
955
+ texture: canvasTexture,
956
+ view: canvasTexture.createView(),
957
+ width,
958
+ height,
959
+ format
960
+ };
961
+ const slots = graphPlan.steps.length > 0
962
+ ? {
963
+ source: ensureSlotTarget('source', width, height),
964
+ target: ensureSlotTarget('target', width, height),
965
+ canvas: canvasSurface
966
+ }
967
+ : null;
968
+ const sceneOutput = slots ? slots.source : canvasSurface;
969
+ const scenePass = commandEncoder.beginRenderPass({
970
+ colorAttachments: [
971
+ {
972
+ view: sceneOutput.view,
973
+ clearValue: {
974
+ r: clearColor[0],
975
+ g: clearColor[1],
976
+ b: clearColor[2],
977
+ a: clearColor[3]
978
+ },
979
+ loadOp: 'clear',
980
+ storeOp: 'store'
981
+ }
982
+ ]
983
+ });
984
+ scenePass.setPipeline(pipeline);
985
+ scenePass.setBindGroup(0, bindGroup);
986
+ scenePass.draw(3);
987
+ scenePass.end();
988
+ if (slots) {
989
+ const resolveStepSurface = (slot) => {
990
+ if (slot === 'source') {
991
+ return slots.source;
992
+ }
993
+ if (slot === 'target') {
994
+ return slots.target;
995
+ }
996
+ if (slot === 'canvas') {
997
+ return slots.canvas;
998
+ }
999
+ const named = runtimeTargets[slot];
1000
+ if (!named) {
1001
+ throw new Error(`Render graph references unknown runtime target "${slot}".`);
1002
+ }
1003
+ return named;
1004
+ };
1005
+ for (const step of graphPlan.steps) {
1006
+ const input = resolveStepSurface(step.input);
1007
+ const output = resolveStepSurface(step.output);
1008
+ step.pass.render({
1009
+ device,
1010
+ commandEncoder,
1011
+ source: slots.source,
1012
+ target: slots.target,
1013
+ canvas: slots.canvas,
1014
+ input,
1015
+ output,
1016
+ targets: runtimeTargets,
1017
+ time,
1018
+ delta,
1019
+ width,
1020
+ height,
1021
+ clear: step.clear,
1022
+ clearColor: step.clearColor,
1023
+ preserve: step.preserve,
1024
+ beginRenderPass: (passOptions) => {
1025
+ const clear = passOptions?.clear ?? step.clear;
1026
+ const clearColor = passOptions?.clearColor ?? step.clearColor;
1027
+ const preserve = passOptions?.preserve ?? step.preserve;
1028
+ return commandEncoder.beginRenderPass({
1029
+ colorAttachments: [
1030
+ {
1031
+ view: passOptions?.view ?? output.view,
1032
+ clearValue: {
1033
+ r: clearColor[0],
1034
+ g: clearColor[1],
1035
+ b: clearColor[2],
1036
+ a: clearColor[3]
1037
+ },
1038
+ loadOp: clear ? 'clear' : 'load',
1039
+ storeOp: preserve ? 'store' : 'discard'
1040
+ }
1041
+ ]
1042
+ });
1043
+ }
1044
+ });
1045
+ if (step.needsSwap) {
1046
+ const previousSource = slots.source;
1047
+ slots.source = slots.target;
1048
+ slots.target = previousSource;
1049
+ }
1050
+ }
1051
+ if (graphPlan.finalOutput !== 'canvas') {
1052
+ const finalSurface = resolveStepSurface(graphPlan.finalOutput);
1053
+ blitToCanvas(commandEncoder, finalSurface.view, slots.canvas.view, clearColor);
1054
+ }
1055
+ }
1056
+ device.queue.submit([commandEncoder.finish()]);
1057
+ };
1058
+ acceptInitializationCleanups = false;
1059
+ initializationCleanups.length = 0;
1060
+ return {
1061
+ render,
1062
+ destroy: () => {
1063
+ isDestroyed = true;
1064
+ device.removeEventListener('uncapturederror', handleUncapturedError);
1065
+ frameBuffer.destroy();
1066
+ uniformBuffer.destroy();
1067
+ destroyRenderTexture(sourceSlotTarget);
1068
+ destroyRenderTexture(targetSlotTarget);
1069
+ for (const target of runtimeRenderTargets.values()) {
1070
+ target.texture.destroy();
1071
+ }
1072
+ runtimeRenderTargets.clear();
1073
+ for (const pass of activePasses) {
1074
+ pass.dispose?.();
1075
+ }
1076
+ activePasses.length = 0;
1077
+ lifecyclePassesRef = null;
1078
+ for (const binding of textureBindings) {
1079
+ binding.texture?.destroy();
1080
+ binding.fallbackTexture.destroy();
1081
+ }
1082
+ blitBindGroupByView = new WeakMap();
1083
+ cachedGraphPlan = null;
1084
+ cachedGraphPasses.length = 0;
1085
+ renderTargetSnapshot = {};
1086
+ renderTargetKeys = [];
1087
+ }
1088
+ };
1089
+ }
1090
+ catch (error) {
1091
+ isDestroyed = true;
1092
+ acceptInitializationCleanups = false;
1093
+ device.removeEventListener('uncapturederror', handleUncapturedError);
1094
+ runInitializationCleanups();
1095
+ throw error;
1096
+ }
1097
+ }