@motion-core/motion-gpu 0.4.0 → 0.4.2

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