@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
@@ -0,0 +1,1547 @@
1
+ import { buildRenderTargetSignature, resolveRenderTargetDefinitions } from './render-targets.js';
2
+ import { planRenderGraph, type RenderGraphPlan } from './render-graph.js';
3
+ import {
4
+ buildShaderSourceWithMap,
5
+ formatShaderSourceLocation,
6
+ type ShaderLineMap
7
+ } from './shader.js';
8
+ import {
9
+ attachShaderCompilationDiagnostics,
10
+ type ShaderCompilationRuntimeContext
11
+ } from './error-diagnostics.js';
12
+ import {
13
+ getTextureMipLevelCount,
14
+ normalizeTextureDefinitions,
15
+ resolveTextureUpdateMode,
16
+ resolveTextureSize,
17
+ toTextureData
18
+ } from './textures.js';
19
+ import { packUniformsInto } from './uniforms.js';
20
+ import type {
21
+ RenderPass,
22
+ RenderPassInputSlot,
23
+ RenderPassOutputSlot,
24
+ RenderMode,
25
+ RenderTarget,
26
+ Renderer,
27
+ RendererOptions,
28
+ TextureSource,
29
+ TextureUpdateMode,
30
+ TextureValue
31
+ } from './types.js';
32
+
33
+ /**
34
+ * Binding index for frame uniforms (`time`, `delta`, `resolution`).
35
+ */
36
+ const FRAME_BINDING = 0;
37
+
38
+ /**
39
+ * Binding index for material uniform buffer.
40
+ */
41
+ const UNIFORM_BINDING = 1;
42
+
43
+ /**
44
+ * First binding index used for texture sampler/texture pairs.
45
+ */
46
+ const FIRST_TEXTURE_BINDING = 2;
47
+
48
+ /**
49
+ * Runtime texture binding state associated with a single texture key.
50
+ */
51
+ interface RuntimeTextureBinding {
52
+ key: string;
53
+ samplerBinding: number;
54
+ textureBinding: number;
55
+ sampler: GPUSampler;
56
+ fallbackTexture: GPUTexture;
57
+ fallbackView: GPUTextureView;
58
+ texture: GPUTexture | null;
59
+ view: GPUTextureView;
60
+ source: TextureSource | null;
61
+ width: number | undefined;
62
+ height: number | undefined;
63
+ mipLevelCount: number;
64
+ format: GPUTextureFormat;
65
+ colorSpace: 'srgb' | 'linear';
66
+ defaultColorSpace: 'srgb' | 'linear';
67
+ flipY: boolean;
68
+ defaultFlipY: boolean;
69
+ generateMipmaps: boolean;
70
+ defaultGenerateMipmaps: boolean;
71
+ premultipliedAlpha: boolean;
72
+ defaultPremultipliedAlpha: boolean;
73
+ update: TextureUpdateMode;
74
+ defaultUpdate?: TextureUpdateMode;
75
+ lastToken: TextureValue;
76
+ }
77
+
78
+ /**
79
+ * Runtime render target allocation metadata.
80
+ */
81
+ interface RuntimeRenderTarget {
82
+ texture: GPUTexture;
83
+ view: GPUTextureView;
84
+ width: number;
85
+ height: number;
86
+ format: GPUTextureFormat;
87
+ }
88
+
89
+ /**
90
+ * Cached pass properties used to validate render-graph cache correctness.
91
+ */
92
+ interface RenderGraphPassSnapshot {
93
+ pass: RenderPass;
94
+ enabled: RenderPass['enabled'];
95
+ needsSwap: RenderPass['needsSwap'];
96
+ input: RenderPass['input'];
97
+ output: RenderPass['output'];
98
+ clear: RenderPass['clear'];
99
+ preserve: RenderPass['preserve'];
100
+ hasClearColor: boolean;
101
+ clearColor0: number;
102
+ clearColor1: number;
103
+ clearColor2: number;
104
+ clearColor3: number;
105
+ }
106
+
107
+ /**
108
+ * Returns sampler/texture binding slots for a texture index.
109
+ */
110
+ function getTextureBindings(index: number): {
111
+ samplerBinding: number;
112
+ textureBinding: number;
113
+ } {
114
+ const samplerBinding = FIRST_TEXTURE_BINDING + index * 2;
115
+ return {
116
+ samplerBinding,
117
+ textureBinding: samplerBinding + 1
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Resizes canvas backing store to match client size and DPR.
123
+ */
124
+ function resizeCanvas(
125
+ canvas: HTMLCanvasElement,
126
+ dprInput: number,
127
+ cssSize?: { width: number; height: number }
128
+ ): { width: number; height: number } {
129
+ const dpr = Number.isFinite(dprInput) && dprInput > 0 ? dprInput : 1;
130
+ const rect = cssSize ? null : canvas.getBoundingClientRect();
131
+ const cssWidth = Math.max(0, cssSize?.width ?? rect?.width ?? 0);
132
+ const cssHeight = Math.max(0, cssSize?.height ?? rect?.height ?? 0);
133
+ const width = Math.max(1, Math.floor((cssWidth || 1) * dpr));
134
+ const height = Math.max(1, Math.floor((cssHeight || 1) * dpr));
135
+
136
+ if (canvas.width !== width || canvas.height !== height) {
137
+ canvas.width = width;
138
+ canvas.height = height;
139
+ }
140
+
141
+ return { width, height };
142
+ }
143
+
144
+ /**
145
+ * Throws when a shader module contains WGSL compilation errors.
146
+ */
147
+ async function assertCompilation(
148
+ module: GPUShaderModule,
149
+ options?: {
150
+ lineMap?: ShaderLineMap;
151
+ fragmentSource?: string;
152
+ includeSources?: Record<string, string>;
153
+ defineBlockSource?: string;
154
+ materialSource?: {
155
+ component?: string;
156
+ file?: string;
157
+ line?: number;
158
+ column?: number;
159
+ functionName?: string;
160
+ } | null;
161
+ runtimeContext?: ShaderCompilationRuntimeContext;
162
+ }
163
+ ): Promise<void> {
164
+ const info = await module.getCompilationInfo();
165
+ const errors = info.messages.filter((message: GPUCompilationMessage) => message.type === 'error');
166
+
167
+ if (errors.length === 0) {
168
+ return;
169
+ }
170
+
171
+ const diagnostics = errors.map((message: GPUCompilationMessage) => ({
172
+ generatedLine: message.lineNum,
173
+ message: message.message,
174
+ linePos: message.linePos,
175
+ lineLength: message.length,
176
+ sourceLocation: options?.lineMap?.[message.lineNum] ?? null
177
+ }));
178
+
179
+ const summary = diagnostics
180
+ .map((diagnostic) => {
181
+ const sourceLabel = formatShaderSourceLocation(diagnostic.sourceLocation);
182
+ const generatedLineLabel =
183
+ diagnostic.generatedLine > 0 ? `generated WGSL line ${diagnostic.generatedLine}` : null;
184
+ const contextLabel = [sourceLabel, generatedLineLabel].filter((value) => Boolean(value));
185
+ if (contextLabel.length === 0) {
186
+ return diagnostic.message;
187
+ }
188
+
189
+ return `[${contextLabel.join(' | ')}] ${diagnostic.message}`;
190
+ })
191
+ .join('\n');
192
+ const error = new Error(`WGSL compilation failed:\n${summary}`);
193
+ throw attachShaderCompilationDiagnostics(error, {
194
+ kind: 'shader-compilation',
195
+ diagnostics,
196
+ fragmentSource: options?.fragmentSource ?? '',
197
+ includeSources: options?.includeSources ?? {},
198
+ ...(options?.defineBlockSource !== undefined
199
+ ? { defineBlockSource: options.defineBlockSource }
200
+ : {}),
201
+ materialSource: options?.materialSource ?? null,
202
+ ...(options?.runtimeContext !== undefined ? { runtimeContext: options.runtimeContext } : {})
203
+ });
204
+ }
205
+
206
+ function toSortedUniqueStrings(values: string[]): string[] {
207
+ return Array.from(new Set(values)).sort((a, b) => a.localeCompare(b));
208
+ }
209
+
210
+ function buildPassGraphSnapshot(
211
+ passes: RenderPass[] | undefined
212
+ ): NonNullable<ShaderCompilationRuntimeContext['passGraph']> {
213
+ const declaredPasses = passes ?? [];
214
+ let enabledPassCount = 0;
215
+ const inputs: string[] = [];
216
+ const outputs: string[] = [];
217
+
218
+ for (const pass of declaredPasses) {
219
+ if (pass.enabled === false) {
220
+ continue;
221
+ }
222
+
223
+ enabledPassCount += 1;
224
+ const needsSwap = pass.needsSwap ?? true;
225
+ const input = pass.input ?? 'source';
226
+ const output = pass.output ?? (needsSwap ? 'target' : 'source');
227
+ inputs.push(input);
228
+ outputs.push(output);
229
+ }
230
+
231
+ return {
232
+ passCount: declaredPasses.length,
233
+ enabledPassCount,
234
+ inputs: toSortedUniqueStrings(inputs),
235
+ outputs: toSortedUniqueStrings(outputs)
236
+ };
237
+ }
238
+
239
+ function buildShaderCompilationRuntimeContext(
240
+ options: RendererOptions
241
+ ): ShaderCompilationRuntimeContext {
242
+ const passList = options.getPasses?.() ?? options.passes;
243
+ const renderTargetMap = options.getRenderTargets?.() ?? options.renderTargets;
244
+
245
+ return {
246
+ ...(options.materialSignature ? { materialSignature: options.materialSignature } : {}),
247
+ passGraph: buildPassGraphSnapshot(passList),
248
+ activeRenderTargets: Object.keys(renderTargetMap ?? {}).sort((a, b) => a.localeCompare(b))
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Creates a 1x1 white fallback texture used before user textures become available.
254
+ */
255
+ function createFallbackTexture(device: GPUDevice, format: GPUTextureFormat): GPUTexture {
256
+ const texture = device.createTexture({
257
+ size: { width: 1, height: 1, depthOrArrayLayers: 1 },
258
+ format,
259
+ usage:
260
+ GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
261
+ });
262
+
263
+ const pixel = new Uint8Array([255, 255, 255, 255]);
264
+ device.queue.writeTexture(
265
+ { texture },
266
+ pixel,
267
+ { offset: 0, bytesPerRow: 4, rowsPerImage: 1 },
268
+ { width: 1, height: 1, depthOrArrayLayers: 1 }
269
+ );
270
+
271
+ return texture;
272
+ }
273
+
274
+ /**
275
+ * Creates an offscreen canvas used for CPU mipmap generation.
276
+ */
277
+ function createMipmapCanvas(width: number, height: number): OffscreenCanvas | HTMLCanvasElement {
278
+ if (typeof OffscreenCanvas !== 'undefined') {
279
+ return new OffscreenCanvas(width, height);
280
+ }
281
+
282
+ const canvas = document.createElement('canvas');
283
+ canvas.width = width;
284
+ canvas.height = height;
285
+ return canvas;
286
+ }
287
+
288
+ /**
289
+ * Creates typed descriptor for `copyExternalImageToTexture`.
290
+ */
291
+ function createExternalCopySource(
292
+ source: CanvasImageSource,
293
+ options: { flipY?: boolean; premultipliedAlpha?: boolean }
294
+ ): GPUCopyExternalImageSourceInfo {
295
+ const descriptor = {
296
+ source,
297
+ ...(options.flipY ? { flipY: true } : {}),
298
+ ...(options.premultipliedAlpha ? { premultipliedAlpha: true } : {})
299
+ };
300
+
301
+ return descriptor as GPUCopyExternalImageSourceInfo;
302
+ }
303
+
304
+ /**
305
+ * Uploads source content to a GPU texture and optionally generates mip chain on CPU.
306
+ */
307
+ function uploadTexture(
308
+ device: GPUDevice,
309
+ texture: GPUTexture,
310
+ binding: Pick<RuntimeTextureBinding, 'flipY' | 'premultipliedAlpha' | 'generateMipmaps'>,
311
+ source: TextureSource,
312
+ width: number,
313
+ height: number,
314
+ mipLevelCount: number
315
+ ): void {
316
+ device.queue.copyExternalImageToTexture(
317
+ createExternalCopySource(source, {
318
+ flipY: binding.flipY,
319
+ premultipliedAlpha: binding.premultipliedAlpha
320
+ }),
321
+ { texture, mipLevel: 0 },
322
+ { width, height, depthOrArrayLayers: 1 }
323
+ );
324
+
325
+ if (!binding.generateMipmaps || mipLevelCount <= 1) {
326
+ return;
327
+ }
328
+
329
+ let previousSource: CanvasImageSource = source;
330
+ let previousWidth = width;
331
+ let previousHeight = height;
332
+
333
+ for (let level = 1; level < mipLevelCount; level += 1) {
334
+ const nextWidth = Math.max(1, Math.floor(previousWidth / 2));
335
+ const nextHeight = Math.max(1, Math.floor(previousHeight / 2));
336
+ const canvas = createMipmapCanvas(nextWidth, nextHeight);
337
+ const context = canvas.getContext('2d');
338
+ if (!context) {
339
+ throw new Error('Unable to create 2D context for mipmap generation');
340
+ }
341
+
342
+ context.drawImage(
343
+ previousSource,
344
+ 0,
345
+ 0,
346
+ previousWidth,
347
+ previousHeight,
348
+ 0,
349
+ 0,
350
+ nextWidth,
351
+ nextHeight
352
+ );
353
+
354
+ device.queue.copyExternalImageToTexture(
355
+ createExternalCopySource(canvas, {
356
+ premultipliedAlpha: binding.premultipliedAlpha
357
+ }),
358
+ { texture, mipLevel: level },
359
+ { width: nextWidth, height: nextHeight, depthOrArrayLayers: 1 }
360
+ );
361
+
362
+ previousSource = canvas;
363
+ previousWidth = nextWidth;
364
+ previousHeight = nextHeight;
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Creates bind group layout entries for frame/uniform buffers plus texture bindings.
370
+ */
371
+ function createBindGroupLayoutEntries(
372
+ textureBindings: RuntimeTextureBinding[]
373
+ ): GPUBindGroupLayoutEntry[] {
374
+ const entries: GPUBindGroupLayoutEntry[] = [
375
+ {
376
+ binding: FRAME_BINDING,
377
+ visibility: GPUShaderStage.FRAGMENT,
378
+ buffer: { type: 'uniform', minBindingSize: 16 }
379
+ },
380
+ {
381
+ binding: UNIFORM_BINDING,
382
+ visibility: GPUShaderStage.FRAGMENT,
383
+ buffer: { type: 'uniform' }
384
+ }
385
+ ];
386
+
387
+ for (const binding of textureBindings) {
388
+ entries.push({
389
+ binding: binding.samplerBinding,
390
+ visibility: GPUShaderStage.FRAGMENT,
391
+ sampler: { type: 'filtering' }
392
+ });
393
+
394
+ entries.push({
395
+ binding: binding.textureBinding,
396
+ visibility: GPUShaderStage.FRAGMENT,
397
+ texture: {
398
+ sampleType: 'float',
399
+ viewDimension: '2d',
400
+ multisampled: false
401
+ }
402
+ });
403
+ }
404
+
405
+ return entries;
406
+ }
407
+
408
+ /**
409
+ * Maximum gap (in floats) between two dirty ranges that triggers merge.
410
+ *
411
+ * Set to 4 (16 bytes) which covers one vec4f alignment slot.
412
+ */
413
+ const DIRTY_RANGE_MERGE_GAP = 4;
414
+
415
+ /**
416
+ * Computes dirty float ranges between two uniform snapshots.
417
+ *
418
+ * Adjacent dirty ranges separated by a gap smaller than or equal to
419
+ * {@link DIRTY_RANGE_MERGE_GAP} are merged to reduce `writeBuffer` calls.
420
+ */
421
+ export function findDirtyFloatRanges(
422
+ previous: Float32Array,
423
+ next: Float32Array,
424
+ mergeGapThreshold = DIRTY_RANGE_MERGE_GAP
425
+ ): Array<{ start: number; count: number }> {
426
+ const ranges: Array<{ start: number; count: number }> = [];
427
+ let start = -1;
428
+
429
+ for (let index = 0; index < next.length; index += 1) {
430
+ if (previous[index] !== next[index]) {
431
+ if (start === -1) {
432
+ start = index;
433
+ }
434
+ continue;
435
+ }
436
+
437
+ if (start !== -1) {
438
+ ranges.push({ start, count: index - start });
439
+ start = -1;
440
+ }
441
+ }
442
+
443
+ if (start !== -1) {
444
+ ranges.push({ start, count: next.length - start });
445
+ }
446
+
447
+ if (ranges.length <= 1) {
448
+ return ranges;
449
+ }
450
+
451
+ const merged: Array<{ start: number; count: number }> = [ranges[0]!];
452
+ for (let index = 1; index < ranges.length; index += 1) {
453
+ const prev = merged[merged.length - 1]!;
454
+ const curr = ranges[index]!;
455
+ const gap = curr.start - (prev.start + prev.count);
456
+
457
+ if (gap <= mergeGapThreshold) {
458
+ prev.count = curr.start + curr.count - prev.start;
459
+ } else {
460
+ merged.push(curr);
461
+ }
462
+ }
463
+
464
+ return merged;
465
+ }
466
+
467
+ /**
468
+ * Determines whether shader output should perform linear-to-sRGB conversion.
469
+ */
470
+ function shouldConvertLinearToSrgb(
471
+ outputColorSpace: 'srgb' | 'linear',
472
+ canvasFormat: GPUTextureFormat
473
+ ): boolean {
474
+ if (outputColorSpace !== 'srgb') {
475
+ return false;
476
+ }
477
+
478
+ return !canvasFormat.endsWith('-srgb');
479
+ }
480
+
481
+ /**
482
+ * WGSL shader used to blit an offscreen texture to the canvas.
483
+ */
484
+ function createFullscreenBlitShader(): string {
485
+ return `
486
+ struct MotionGPUVertexOut {
487
+ @builtin(position) position: vec4f,
488
+ @location(0) uv: vec2f,
489
+ };
490
+
491
+ @group(0) @binding(0) var motiongpuBlitSampler: sampler;
492
+ @group(0) @binding(1) var motiongpuBlitTexture: texture_2d<f32>;
493
+
494
+ @vertex
495
+ fn motiongpuBlitVertex(@builtin(vertex_index) index: u32) -> MotionGPUVertexOut {
496
+ var positions = array<vec2f, 3>(
497
+ vec2f(-1.0, -3.0),
498
+ vec2f(-1.0, 1.0),
499
+ vec2f(3.0, 1.0)
500
+ );
501
+
502
+ let position = positions[index];
503
+ var out: MotionGPUVertexOut;
504
+ out.position = vec4f(position, 0.0, 1.0);
505
+ out.uv = (position + vec2f(1.0, 1.0)) * 0.5;
506
+ return out;
507
+ }
508
+
509
+ @fragment
510
+ fn motiongpuBlitFragment(in: MotionGPUVertexOut) -> @location(0) vec4f {
511
+ return textureSample(motiongpuBlitTexture, motiongpuBlitSampler, in.uv);
512
+ }
513
+ `;
514
+ }
515
+
516
+ /**
517
+ * Allocates a render target texture with usage flags suitable for passes/blits.
518
+ */
519
+ function createRenderTexture(
520
+ device: GPUDevice,
521
+ width: number,
522
+ height: number,
523
+ format: GPUTextureFormat
524
+ ): RuntimeRenderTarget {
525
+ const texture = device.createTexture({
526
+ size: { width, height, depthOrArrayLayers: 1 },
527
+ format,
528
+ usage:
529
+ GPUTextureUsage.TEXTURE_BINDING |
530
+ GPUTextureUsage.RENDER_ATTACHMENT |
531
+ GPUTextureUsage.COPY_DST |
532
+ GPUTextureUsage.COPY_SRC
533
+ });
534
+
535
+ return {
536
+ texture,
537
+ view: texture.createView(),
538
+ width,
539
+ height,
540
+ format
541
+ };
542
+ }
543
+
544
+ /**
545
+ * Destroys a render target texture if present.
546
+ */
547
+ function destroyRenderTexture(target: RuntimeRenderTarget | null): void {
548
+ target?.texture.destroy();
549
+ }
550
+
551
+ /**
552
+ * Creates the WebGPU renderer used by `FragCanvas`.
553
+ *
554
+ * @param options - Renderer creation options resolved from material/context state.
555
+ * @returns Renderer instance with `render` and `destroy`.
556
+ * @throws {Error} On WebGPU unavailability, shader compilation issues, or runtime setup failures.
557
+ */
558
+ export async function createRenderer(options: RendererOptions): Promise<Renderer> {
559
+ if (!navigator.gpu) {
560
+ throw new Error('WebGPU is not available in this browser');
561
+ }
562
+
563
+ const context = options.canvas.getContext('webgpu') as GPUCanvasContext | null;
564
+ if (!context) {
565
+ throw new Error('Canvas does not support webgpu context');
566
+ }
567
+
568
+ const format = navigator.gpu.getPreferredCanvasFormat();
569
+ const adapter = await navigator.gpu.requestAdapter(options.adapterOptions);
570
+ if (!adapter) {
571
+ throw new Error('Unable to acquire WebGPU adapter');
572
+ }
573
+
574
+ const device = await adapter.requestDevice(options.deviceDescriptor);
575
+ let isDestroyed = false;
576
+ let deviceLostMessage: string | null = null;
577
+ let uncapturedErrorMessage: string | null = null;
578
+ const initializationCleanups: Array<() => void> = [];
579
+ let acceptInitializationCleanups = true;
580
+
581
+ const registerInitializationCleanup = (cleanup: () => void): void => {
582
+ if (!acceptInitializationCleanups) {
583
+ return;
584
+ }
585
+ options.__onInitializationCleanupRegistered?.();
586
+ initializationCleanups.push(cleanup);
587
+ };
588
+
589
+ const runInitializationCleanups = (): void => {
590
+ for (let index = initializationCleanups.length - 1; index >= 0; index -= 1) {
591
+ try {
592
+ initializationCleanups[index]?.();
593
+ } catch {
594
+ // Best-effort cleanup on failed renderer initialization.
595
+ }
596
+ }
597
+ initializationCleanups.length = 0;
598
+ };
599
+
600
+ void device.lost.then((info) => {
601
+ if (isDestroyed) {
602
+ return;
603
+ }
604
+
605
+ const reason = info.reason ? ` (${info.reason})` : '';
606
+ const details = info.message?.trim();
607
+ deviceLostMessage = details
608
+ ? `WebGPU device lost: ${details}${reason}`
609
+ : `WebGPU device lost${reason}`;
610
+ });
611
+
612
+ const handleUncapturedError = (event: GPUUncapturedErrorEvent): void => {
613
+ if (isDestroyed) {
614
+ return;
615
+ }
616
+
617
+ const message =
618
+ event.error instanceof Error
619
+ ? event.error.message
620
+ : String((event.error as { message?: string })?.message ?? event.error);
621
+ uncapturedErrorMessage = `WebGPU uncaptured error: ${message}`;
622
+ };
623
+
624
+ device.addEventListener('uncapturederror', handleUncapturedError);
625
+ try {
626
+ const runtimeContext = buildShaderCompilationRuntimeContext(options);
627
+ const convertLinearToSrgb = shouldConvertLinearToSrgb(options.outputColorSpace, format);
628
+ const builtShader = buildShaderSourceWithMap(
629
+ options.fragmentWgsl,
630
+ options.uniformLayout,
631
+ options.textureKeys,
632
+ {
633
+ convertLinearToSrgb,
634
+ fragmentLineMap: options.fragmentLineMap
635
+ }
636
+ );
637
+ const shaderModule = device.createShaderModule({ code: builtShader.code });
638
+ await assertCompilation(shaderModule, {
639
+ lineMap: builtShader.lineMap,
640
+ fragmentSource: options.fragmentSource,
641
+ includeSources: options.includeSources,
642
+ ...(options.defineBlockSource !== undefined
643
+ ? { defineBlockSource: options.defineBlockSource }
644
+ : {}),
645
+ materialSource: options.materialSource ?? null,
646
+ runtimeContext
647
+ });
648
+
649
+ const normalizedTextureDefinitions = normalizeTextureDefinitions(
650
+ options.textureDefinitions,
651
+ options.textureKeys
652
+ );
653
+ const textureBindings = options.textureKeys.map((key, index): RuntimeTextureBinding => {
654
+ const config = normalizedTextureDefinitions[key];
655
+ if (!config) {
656
+ throw new Error(`Missing texture definition for "${key}"`);
657
+ }
658
+
659
+ const { samplerBinding, textureBinding } = getTextureBindings(index);
660
+ const sampler = device.createSampler({
661
+ magFilter: config.filter,
662
+ minFilter: config.filter,
663
+ mipmapFilter: config.generateMipmaps ? config.filter : 'nearest',
664
+ addressModeU: config.addressModeU,
665
+ addressModeV: config.addressModeV,
666
+ maxAnisotropy: config.filter === 'linear' ? config.anisotropy : 1
667
+ });
668
+ const fallbackTexture = createFallbackTexture(device, config.format);
669
+ registerInitializationCleanup(() => {
670
+ fallbackTexture.destroy();
671
+ });
672
+ const fallbackView = fallbackTexture.createView();
673
+
674
+ const runtimeBinding: RuntimeTextureBinding = {
675
+ key,
676
+ samplerBinding,
677
+ textureBinding,
678
+ sampler,
679
+ fallbackTexture,
680
+ fallbackView,
681
+ texture: null,
682
+ view: fallbackView,
683
+ source: null,
684
+ width: undefined,
685
+ height: undefined,
686
+ mipLevelCount: 1,
687
+ format: config.format,
688
+ colorSpace: config.colorSpace,
689
+ defaultColorSpace: config.colorSpace,
690
+ flipY: config.flipY,
691
+ defaultFlipY: config.flipY,
692
+ generateMipmaps: config.generateMipmaps,
693
+ defaultGenerateMipmaps: config.generateMipmaps,
694
+ premultipliedAlpha: config.premultipliedAlpha,
695
+ defaultPremultipliedAlpha: config.premultipliedAlpha,
696
+ update: config.update ?? 'once',
697
+ lastToken: null
698
+ };
699
+
700
+ if (config.update !== undefined) {
701
+ runtimeBinding.defaultUpdate = config.update;
702
+ }
703
+
704
+ return runtimeBinding;
705
+ });
706
+
707
+ const bindGroupLayout = device.createBindGroupLayout({
708
+ entries: createBindGroupLayoutEntries(textureBindings)
709
+ });
710
+ const pipelineLayout = device.createPipelineLayout({
711
+ bindGroupLayouts: [bindGroupLayout]
712
+ });
713
+
714
+ const pipeline = device.createRenderPipeline({
715
+ layout: pipelineLayout,
716
+ vertex: {
717
+ module: shaderModule,
718
+ entryPoint: 'motiongpuVertex'
719
+ },
720
+ fragment: {
721
+ module: shaderModule,
722
+ entryPoint: 'motiongpuFragment',
723
+ targets: [{ format }]
724
+ },
725
+ primitive: {
726
+ topology: 'triangle-list'
727
+ }
728
+ });
729
+
730
+ const blitShaderModule = device.createShaderModule({
731
+ code: createFullscreenBlitShader()
732
+ });
733
+ await assertCompilation(blitShaderModule);
734
+
735
+ const blitBindGroupLayout = device.createBindGroupLayout({
736
+ entries: [
737
+ {
738
+ binding: 0,
739
+ visibility: GPUShaderStage.FRAGMENT,
740
+ sampler: { type: 'filtering' }
741
+ },
742
+ {
743
+ binding: 1,
744
+ visibility: GPUShaderStage.FRAGMENT,
745
+ texture: {
746
+ sampleType: 'float',
747
+ viewDimension: '2d',
748
+ multisampled: false
749
+ }
750
+ }
751
+ ]
752
+ });
753
+ const blitPipelineLayout = device.createPipelineLayout({
754
+ bindGroupLayouts: [blitBindGroupLayout]
755
+ });
756
+ const blitPipeline = device.createRenderPipeline({
757
+ layout: blitPipelineLayout,
758
+ vertex: { module: blitShaderModule, entryPoint: 'motiongpuBlitVertex' },
759
+ fragment: {
760
+ module: blitShaderModule,
761
+ entryPoint: 'motiongpuBlitFragment',
762
+ targets: [{ format }]
763
+ },
764
+ primitive: {
765
+ topology: 'triangle-list'
766
+ }
767
+ });
768
+ const blitSampler = device.createSampler({
769
+ magFilter: 'linear',
770
+ minFilter: 'linear',
771
+ addressModeU: 'clamp-to-edge',
772
+ addressModeV: 'clamp-to-edge'
773
+ });
774
+ let blitBindGroupByView = new WeakMap<GPUTextureView, GPUBindGroup>();
775
+
776
+ const frameBuffer = device.createBuffer({
777
+ size: 16,
778
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
779
+ });
780
+ registerInitializationCleanup(() => {
781
+ frameBuffer.destroy();
782
+ });
783
+
784
+ const uniformBuffer = device.createBuffer({
785
+ size: options.uniformLayout.byteLength,
786
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
787
+ });
788
+ registerInitializationCleanup(() => {
789
+ uniformBuffer.destroy();
790
+ });
791
+ const frameScratch = new Float32Array(4);
792
+ const uniformScratch = new Float32Array(options.uniformLayout.byteLength / 4);
793
+ const uniformPrevious = new Float32Array(options.uniformLayout.byteLength / 4);
794
+ let hasUniformSnapshot = false;
795
+
796
+ /**
797
+ * Rebuilds bind group using current texture views.
798
+ */
799
+ const createBindGroup = (): GPUBindGroup => {
800
+ const entries: GPUBindGroupEntry[] = [
801
+ { binding: FRAME_BINDING, resource: { buffer: frameBuffer } },
802
+ { binding: UNIFORM_BINDING, resource: { buffer: uniformBuffer } }
803
+ ];
804
+
805
+ for (const binding of textureBindings) {
806
+ entries.push({
807
+ binding: binding.samplerBinding,
808
+ resource: binding.sampler
809
+ });
810
+ entries.push({
811
+ binding: binding.textureBinding,
812
+ resource: binding.view
813
+ });
814
+ }
815
+
816
+ return device.createBindGroup({
817
+ layout: bindGroupLayout,
818
+ entries
819
+ });
820
+ };
821
+
822
+ /**
823
+ * Synchronizes one runtime texture binding with incoming texture value.
824
+ *
825
+ * @returns `true` when bind group must be rebuilt.
826
+ */
827
+ const updateTextureBinding = (
828
+ binding: RuntimeTextureBinding,
829
+ value: TextureValue,
830
+ renderMode: RenderMode
831
+ ): boolean => {
832
+ const nextData = toTextureData(value);
833
+
834
+ if (!nextData) {
835
+ if (binding.source === null && binding.texture === null) {
836
+ return false;
837
+ }
838
+
839
+ binding.texture?.destroy();
840
+ binding.texture = null;
841
+ binding.view = binding.fallbackView;
842
+ binding.source = null;
843
+ binding.width = undefined;
844
+ binding.height = undefined;
845
+ binding.lastToken = null;
846
+ return true;
847
+ }
848
+
849
+ const source = nextData.source;
850
+ const colorSpace = nextData.colorSpace ?? binding.defaultColorSpace;
851
+ const format = colorSpace === 'linear' ? 'rgba8unorm' : 'rgba8unorm-srgb';
852
+ const flipY = nextData.flipY ?? binding.defaultFlipY;
853
+ const premultipliedAlpha = nextData.premultipliedAlpha ?? binding.defaultPremultipliedAlpha;
854
+ const generateMipmaps = nextData.generateMipmaps ?? binding.defaultGenerateMipmaps;
855
+ const update = resolveTextureUpdateMode({
856
+ source,
857
+ ...(nextData.update !== undefined ? { override: nextData.update } : {}),
858
+ ...(binding.defaultUpdate !== undefined ? { defaultMode: binding.defaultUpdate } : {})
859
+ });
860
+ const { width, height } = resolveTextureSize(nextData);
861
+ const mipLevelCount = generateMipmaps ? getTextureMipLevelCount(width, height) : 1;
862
+ const sourceChanged = binding.source !== source;
863
+ const tokenChanged = binding.lastToken !== value;
864
+ const requiresReallocation =
865
+ binding.texture === null ||
866
+ binding.width !== width ||
867
+ binding.height !== height ||
868
+ binding.mipLevelCount !== mipLevelCount ||
869
+ binding.format !== format;
870
+
871
+ if (!requiresReallocation) {
872
+ const shouldUpload =
873
+ sourceChanged ||
874
+ update === 'perFrame' ||
875
+ (update === 'onInvalidate' && (renderMode !== 'always' || tokenChanged));
876
+
877
+ if (shouldUpload && binding.texture) {
878
+ binding.flipY = flipY;
879
+ binding.generateMipmaps = generateMipmaps;
880
+ binding.premultipliedAlpha = premultipliedAlpha;
881
+ binding.colorSpace = colorSpace;
882
+ uploadTexture(device, binding.texture, binding, source, width, height, mipLevelCount);
883
+ }
884
+
885
+ binding.source = source;
886
+ binding.width = width;
887
+ binding.height = height;
888
+ binding.mipLevelCount = mipLevelCount;
889
+ binding.update = update;
890
+ binding.lastToken = value;
891
+ return false;
892
+ }
893
+
894
+ const texture = device.createTexture({
895
+ size: { width, height, depthOrArrayLayers: 1 },
896
+ format,
897
+ mipLevelCount,
898
+ usage:
899
+ GPUTextureUsage.TEXTURE_BINDING |
900
+ GPUTextureUsage.COPY_DST |
901
+ GPUTextureUsage.RENDER_ATTACHMENT
902
+ });
903
+ registerInitializationCleanup(() => {
904
+ texture.destroy();
905
+ });
906
+
907
+ binding.flipY = flipY;
908
+ binding.generateMipmaps = generateMipmaps;
909
+ binding.premultipliedAlpha = premultipliedAlpha;
910
+ binding.colorSpace = colorSpace;
911
+ binding.format = format;
912
+ uploadTexture(device, texture, binding, source, width, height, mipLevelCount);
913
+
914
+ binding.texture?.destroy();
915
+ binding.texture = texture;
916
+ binding.view = texture.createView();
917
+ binding.source = source;
918
+ binding.width = width;
919
+ binding.height = height;
920
+ binding.mipLevelCount = mipLevelCount;
921
+ binding.update = update;
922
+ binding.lastToken = value;
923
+ return true;
924
+ };
925
+
926
+ for (const binding of textureBindings) {
927
+ const defaultSource = normalizedTextureDefinitions[binding.key]?.source ?? null;
928
+ updateTextureBinding(binding, defaultSource, 'always');
929
+ }
930
+
931
+ let bindGroup = createBindGroup();
932
+ let sourceSlotTarget: RuntimeRenderTarget | null = null;
933
+ let targetSlotTarget: RuntimeRenderTarget | null = null;
934
+ let renderTargetSignature = '';
935
+ let renderTargetSnapshot: Readonly<Record<string, RenderTarget>> = {};
936
+ let renderTargetKeys: string[] = [];
937
+ let cachedGraphPlan: RenderGraphPlan | null = null;
938
+ let cachedGraphRenderTargetSignature = '';
939
+ const cachedGraphClearColor: [number, number, number, number] = [NaN, NaN, NaN, NaN];
940
+ const cachedGraphPasses: RenderGraphPassSnapshot[] = [];
941
+ let contextConfigured = false;
942
+ let configuredWidth = 0;
943
+ let configuredHeight = 0;
944
+ const runtimeRenderTargets = new Map<string, RuntimeRenderTarget>();
945
+ const activePasses: RenderPass[] = [];
946
+ const lifecyclePreviousSet = new Set<RenderPass>();
947
+ const lifecycleNextSet = new Set<RenderPass>();
948
+ const lifecycleUniquePasses: RenderPass[] = [];
949
+ let lifecyclePassesRef: RenderPass[] | null = null;
950
+ let passWidth = 0;
951
+ let passHeight = 0;
952
+
953
+ /**
954
+ * Resolves active render pass list for current frame.
955
+ */
956
+ const resolvePasses = (): RenderPass[] => {
957
+ return options.getPasses?.() ?? options.passes ?? [];
958
+ };
959
+
960
+ /**
961
+ * Resolves active render target declarations for current frame.
962
+ */
963
+ const resolveRenderTargets = () => {
964
+ return options.getRenderTargets?.() ?? options.renderTargets;
965
+ };
966
+
967
+ /**
968
+ * Checks whether cached render-graph plan can be reused for this frame.
969
+ */
970
+ const isGraphPlanCacheValid = (
971
+ passes: RenderPass[],
972
+ clearColor: [number, number, number, number]
973
+ ): boolean => {
974
+ if (!cachedGraphPlan) {
975
+ return false;
976
+ }
977
+
978
+ if (cachedGraphRenderTargetSignature !== renderTargetSignature) {
979
+ return false;
980
+ }
981
+
982
+ if (
983
+ cachedGraphClearColor[0] !== clearColor[0] ||
984
+ cachedGraphClearColor[1] !== clearColor[1] ||
985
+ cachedGraphClearColor[2] !== clearColor[2] ||
986
+ cachedGraphClearColor[3] !== clearColor[3]
987
+ ) {
988
+ return false;
989
+ }
990
+
991
+ if (cachedGraphPasses.length !== passes.length) {
992
+ return false;
993
+ }
994
+
995
+ for (let index = 0; index < passes.length; index += 1) {
996
+ const pass = passes[index];
997
+ const snapshot = cachedGraphPasses[index];
998
+ if (!pass || !snapshot || snapshot.pass !== pass) {
999
+ return false;
1000
+ }
1001
+
1002
+ if (
1003
+ snapshot.enabled !== pass.enabled ||
1004
+ snapshot.needsSwap !== pass.needsSwap ||
1005
+ snapshot.input !== pass.input ||
1006
+ snapshot.output !== pass.output ||
1007
+ snapshot.clear !== pass.clear ||
1008
+ snapshot.preserve !== pass.preserve
1009
+ ) {
1010
+ return false;
1011
+ }
1012
+
1013
+ const passClearColor = pass.clearColor;
1014
+ const hasPassClearColor = passClearColor !== undefined;
1015
+ if (snapshot.hasClearColor !== hasPassClearColor) {
1016
+ return false;
1017
+ }
1018
+
1019
+ if (passClearColor) {
1020
+ if (
1021
+ snapshot.clearColor0 !== passClearColor[0] ||
1022
+ snapshot.clearColor1 !== passClearColor[1] ||
1023
+ snapshot.clearColor2 !== passClearColor[2] ||
1024
+ snapshot.clearColor3 !== passClearColor[3]
1025
+ ) {
1026
+ return false;
1027
+ }
1028
+ }
1029
+ }
1030
+
1031
+ return true;
1032
+ };
1033
+
1034
+ /**
1035
+ * Updates render-graph cache with current pass set.
1036
+ */
1037
+ const updateGraphPlanCache = (
1038
+ passes: RenderPass[],
1039
+ clearColor: [number, number, number, number],
1040
+ graphPlan: RenderGraphPlan
1041
+ ): void => {
1042
+ cachedGraphPlan = graphPlan;
1043
+ cachedGraphRenderTargetSignature = renderTargetSignature;
1044
+ cachedGraphClearColor[0] = clearColor[0];
1045
+ cachedGraphClearColor[1] = clearColor[1];
1046
+ cachedGraphClearColor[2] = clearColor[2];
1047
+ cachedGraphClearColor[3] = clearColor[3];
1048
+ cachedGraphPasses.length = passes.length;
1049
+
1050
+ let index = 0;
1051
+ for (const pass of passes) {
1052
+ const passClearColor = pass.clearColor;
1053
+ const hasPassClearColor = passClearColor !== undefined;
1054
+ const snapshot = cachedGraphPasses[index];
1055
+ if (!snapshot) {
1056
+ cachedGraphPasses[index] = {
1057
+ pass,
1058
+ enabled: pass.enabled,
1059
+ needsSwap: pass.needsSwap,
1060
+ input: pass.input,
1061
+ output: pass.output,
1062
+ clear: pass.clear,
1063
+ preserve: pass.preserve,
1064
+ hasClearColor: hasPassClearColor,
1065
+ clearColor0: passClearColor?.[0] ?? 0,
1066
+ clearColor1: passClearColor?.[1] ?? 0,
1067
+ clearColor2: passClearColor?.[2] ?? 0,
1068
+ clearColor3: passClearColor?.[3] ?? 0
1069
+ };
1070
+ index += 1;
1071
+ continue;
1072
+ }
1073
+
1074
+ snapshot.pass = pass;
1075
+ snapshot.enabled = pass.enabled;
1076
+ snapshot.needsSwap = pass.needsSwap;
1077
+ snapshot.input = pass.input;
1078
+ snapshot.output = pass.output;
1079
+ snapshot.clear = pass.clear;
1080
+ snapshot.preserve = pass.preserve;
1081
+ snapshot.hasClearColor = hasPassClearColor;
1082
+ snapshot.clearColor0 = passClearColor?.[0] ?? 0;
1083
+ snapshot.clearColor1 = passClearColor?.[1] ?? 0;
1084
+ snapshot.clearColor2 = passClearColor?.[2] ?? 0;
1085
+ snapshot.clearColor3 = passClearColor?.[3] ?? 0;
1086
+ index += 1;
1087
+ }
1088
+ };
1089
+
1090
+ /**
1091
+ * Synchronizes pass lifecycle callbacks and resize notifications.
1092
+ */
1093
+ const syncPassLifecycle = (passes: RenderPass[], width: number, height: number): void => {
1094
+ const resized = passWidth !== width || passHeight !== height;
1095
+ if (!resized && lifecyclePassesRef === passes && passes.length === activePasses.length) {
1096
+ let isSameOrder = true;
1097
+ for (let index = 0; index < passes.length; index += 1) {
1098
+ if (activePasses[index] !== passes[index]) {
1099
+ isSameOrder = false;
1100
+ break;
1101
+ }
1102
+ }
1103
+
1104
+ if (isSameOrder) {
1105
+ return;
1106
+ }
1107
+ }
1108
+
1109
+ lifecycleNextSet.clear();
1110
+ lifecycleUniquePasses.length = 0;
1111
+ for (const pass of passes) {
1112
+ if (lifecycleNextSet.has(pass)) {
1113
+ continue;
1114
+ }
1115
+
1116
+ lifecycleNextSet.add(pass);
1117
+ lifecycleUniquePasses.push(pass);
1118
+ }
1119
+ lifecyclePreviousSet.clear();
1120
+ for (const pass of activePasses) {
1121
+ lifecyclePreviousSet.add(pass);
1122
+ }
1123
+
1124
+ for (const pass of activePasses) {
1125
+ if (!lifecycleNextSet.has(pass)) {
1126
+ pass.dispose?.();
1127
+ }
1128
+ }
1129
+
1130
+ for (const pass of lifecycleUniquePasses) {
1131
+ if (resized || !lifecyclePreviousSet.has(pass)) {
1132
+ pass.setSize?.(width, height);
1133
+ }
1134
+ }
1135
+
1136
+ activePasses.length = 0;
1137
+ for (const pass of lifecycleUniquePasses) {
1138
+ activePasses.push(pass);
1139
+ }
1140
+ lifecyclePassesRef = passes;
1141
+ passWidth = width;
1142
+ passHeight = height;
1143
+ };
1144
+
1145
+ /**
1146
+ * Ensures internal ping-pong slot texture matches current canvas size/format.
1147
+ */
1148
+ const ensureSlotTarget = (
1149
+ slot: RenderPassInputSlot,
1150
+ width: number,
1151
+ height: number
1152
+ ): RuntimeRenderTarget => {
1153
+ const current = slot === 'source' ? sourceSlotTarget : targetSlotTarget;
1154
+ if (
1155
+ current &&
1156
+ current.width === width &&
1157
+ current.height === height &&
1158
+ current.format === format
1159
+ ) {
1160
+ return current;
1161
+ }
1162
+
1163
+ destroyRenderTexture(current);
1164
+ const next = createRenderTexture(device, width, height, format);
1165
+ if (slot === 'source') {
1166
+ sourceSlotTarget = next;
1167
+ } else {
1168
+ targetSlotTarget = next;
1169
+ }
1170
+
1171
+ return next;
1172
+ };
1173
+
1174
+ /**
1175
+ * Creates/updates runtime render targets and returns immutable pass snapshot.
1176
+ */
1177
+ const syncRenderTargets = (
1178
+ canvasWidth: number,
1179
+ canvasHeight: number
1180
+ ): Readonly<Record<string, RenderTarget>> => {
1181
+ const resolvedDefinitions = resolveRenderTargetDefinitions(
1182
+ resolveRenderTargets(),
1183
+ canvasWidth,
1184
+ canvasHeight,
1185
+ format
1186
+ );
1187
+ const nextSignature = buildRenderTargetSignature(resolvedDefinitions);
1188
+
1189
+ if (nextSignature !== renderTargetSignature) {
1190
+ const activeKeys = new Set(resolvedDefinitions.map((definition) => definition.key));
1191
+
1192
+ for (const [key, target] of runtimeRenderTargets.entries()) {
1193
+ if (!activeKeys.has(key)) {
1194
+ target.texture.destroy();
1195
+ runtimeRenderTargets.delete(key);
1196
+ }
1197
+ }
1198
+
1199
+ for (const definition of resolvedDefinitions) {
1200
+ const current = runtimeRenderTargets.get(definition.key);
1201
+ if (
1202
+ current &&
1203
+ current.width === definition.width &&
1204
+ current.height === definition.height &&
1205
+ current.format === definition.format
1206
+ ) {
1207
+ continue;
1208
+ }
1209
+
1210
+ current?.texture.destroy();
1211
+ runtimeRenderTargets.set(
1212
+ definition.key,
1213
+ createRenderTexture(device, definition.width, definition.height, definition.format)
1214
+ );
1215
+ }
1216
+
1217
+ renderTargetSignature = nextSignature;
1218
+ const nextSnapshot: Record<string, RenderTarget> = {};
1219
+ const nextKeys: string[] = [];
1220
+ for (const definition of resolvedDefinitions) {
1221
+ const target = runtimeRenderTargets.get(definition.key);
1222
+ if (!target) {
1223
+ continue;
1224
+ }
1225
+
1226
+ nextKeys.push(definition.key);
1227
+ nextSnapshot[definition.key] = {
1228
+ texture: target.texture,
1229
+ view: target.view,
1230
+ width: target.width,
1231
+ height: target.height,
1232
+ format: target.format
1233
+ };
1234
+ }
1235
+
1236
+ renderTargetSnapshot = nextSnapshot;
1237
+ renderTargetKeys = nextKeys;
1238
+ }
1239
+
1240
+ return renderTargetSnapshot;
1241
+ };
1242
+
1243
+ /**
1244
+ * Blits a texture view to the current canvas texture.
1245
+ */
1246
+ const blitToCanvas = (
1247
+ commandEncoder: GPUCommandEncoder,
1248
+ sourceView: GPUTextureView,
1249
+ canvasView: GPUTextureView,
1250
+ clearColor: [number, number, number, number]
1251
+ ): void => {
1252
+ let bindGroup = blitBindGroupByView.get(sourceView);
1253
+ if (!bindGroup) {
1254
+ bindGroup = device.createBindGroup({
1255
+ layout: blitBindGroupLayout,
1256
+ entries: [
1257
+ { binding: 0, resource: blitSampler },
1258
+ { binding: 1, resource: sourceView }
1259
+ ]
1260
+ });
1261
+ blitBindGroupByView.set(sourceView, bindGroup);
1262
+ }
1263
+
1264
+ const pass = commandEncoder.beginRenderPass({
1265
+ colorAttachments: [
1266
+ {
1267
+ view: canvasView,
1268
+ clearValue: {
1269
+ r: clearColor[0],
1270
+ g: clearColor[1],
1271
+ b: clearColor[2],
1272
+ a: clearColor[3]
1273
+ },
1274
+ loadOp: 'clear',
1275
+ storeOp: 'store'
1276
+ }
1277
+ ]
1278
+ });
1279
+
1280
+ pass.setPipeline(blitPipeline);
1281
+ pass.setBindGroup(0, bindGroup);
1282
+ pass.draw(3);
1283
+ pass.end();
1284
+ };
1285
+
1286
+ /**
1287
+ * Executes a full frame render.
1288
+ */
1289
+ const render: Renderer['render'] = ({
1290
+ time,
1291
+ delta,
1292
+ renderMode,
1293
+ uniforms,
1294
+ textures,
1295
+ canvasSize
1296
+ }) => {
1297
+ if (deviceLostMessage) {
1298
+ throw new Error(deviceLostMessage);
1299
+ }
1300
+
1301
+ if (uncapturedErrorMessage) {
1302
+ const message = uncapturedErrorMessage;
1303
+ uncapturedErrorMessage = null;
1304
+ throw new Error(message);
1305
+ }
1306
+
1307
+ const { width, height } = resizeCanvas(options.canvas, options.getDpr(), canvasSize);
1308
+
1309
+ if (!contextConfigured || configuredWidth !== width || configuredHeight !== height) {
1310
+ context.configure({
1311
+ device,
1312
+ format,
1313
+ alphaMode: 'premultiplied'
1314
+ });
1315
+ contextConfigured = true;
1316
+ configuredWidth = width;
1317
+ configuredHeight = height;
1318
+ }
1319
+
1320
+ frameScratch[0] = time;
1321
+ frameScratch[1] = delta;
1322
+ frameScratch[2] = width;
1323
+ frameScratch[3] = height;
1324
+ device.queue.writeBuffer(
1325
+ frameBuffer,
1326
+ 0,
1327
+ frameScratch.buffer as ArrayBuffer,
1328
+ frameScratch.byteOffset,
1329
+ frameScratch.byteLength
1330
+ );
1331
+
1332
+ packUniformsInto(uniforms, options.uniformLayout, uniformScratch);
1333
+ if (!hasUniformSnapshot) {
1334
+ device.queue.writeBuffer(
1335
+ uniformBuffer,
1336
+ 0,
1337
+ uniformScratch.buffer as ArrayBuffer,
1338
+ uniformScratch.byteOffset,
1339
+ uniformScratch.byteLength
1340
+ );
1341
+ uniformPrevious.set(uniformScratch);
1342
+ hasUniformSnapshot = true;
1343
+ } else {
1344
+ const dirtyRanges = findDirtyFloatRanges(uniformPrevious, uniformScratch);
1345
+ for (const range of dirtyRanges) {
1346
+ const byteOffset = range.start * 4;
1347
+ const byteLength = range.count * 4;
1348
+ device.queue.writeBuffer(
1349
+ uniformBuffer,
1350
+ byteOffset,
1351
+ uniformScratch.buffer as ArrayBuffer,
1352
+ uniformScratch.byteOffset + byteOffset,
1353
+ byteLength
1354
+ );
1355
+ }
1356
+
1357
+ if (dirtyRanges.length > 0) {
1358
+ uniformPrevious.set(uniformScratch);
1359
+ }
1360
+ }
1361
+
1362
+ let bindGroupDirty = false;
1363
+ for (const binding of textureBindings) {
1364
+ const nextTexture =
1365
+ textures[binding.key] ?? normalizedTextureDefinitions[binding.key]?.source ?? null;
1366
+ if (updateTextureBinding(binding, nextTexture, renderMode)) {
1367
+ bindGroupDirty = true;
1368
+ }
1369
+ }
1370
+
1371
+ if (bindGroupDirty) {
1372
+ bindGroup = createBindGroup();
1373
+ }
1374
+
1375
+ const commandEncoder = device.createCommandEncoder();
1376
+ const passes = resolvePasses();
1377
+ const clearColor = options.getClearColor();
1378
+ syncPassLifecycle(passes, width, height);
1379
+ const runtimeTargets = syncRenderTargets(width, height);
1380
+ const graphPlan = isGraphPlanCacheValid(passes, clearColor)
1381
+ ? cachedGraphPlan!
1382
+ : (() => {
1383
+ const nextPlan = planRenderGraph(passes, clearColor, renderTargetKeys);
1384
+ updateGraphPlanCache(passes, clearColor, nextPlan);
1385
+ return nextPlan;
1386
+ })();
1387
+ const canvasTexture = context.getCurrentTexture();
1388
+ const canvasSurface: RenderTarget = {
1389
+ texture: canvasTexture,
1390
+ view: canvasTexture.createView(),
1391
+ width,
1392
+ height,
1393
+ format
1394
+ };
1395
+ const slots =
1396
+ graphPlan.steps.length > 0
1397
+ ? {
1398
+ source: ensureSlotTarget('source', width, height),
1399
+ target: ensureSlotTarget('target', width, height),
1400
+ canvas: canvasSurface
1401
+ }
1402
+ : null;
1403
+ const sceneOutput = slots ? slots.source : canvasSurface;
1404
+
1405
+ const scenePass = commandEncoder.beginRenderPass({
1406
+ colorAttachments: [
1407
+ {
1408
+ view: sceneOutput.view,
1409
+ clearValue: {
1410
+ r: clearColor[0],
1411
+ g: clearColor[1],
1412
+ b: clearColor[2],
1413
+ a: clearColor[3]
1414
+ },
1415
+ loadOp: 'clear',
1416
+ storeOp: 'store'
1417
+ }
1418
+ ]
1419
+ });
1420
+
1421
+ scenePass.setPipeline(pipeline);
1422
+ scenePass.setBindGroup(0, bindGroup);
1423
+ scenePass.draw(3);
1424
+ scenePass.end();
1425
+
1426
+ if (slots) {
1427
+ const resolveStepSurface = (
1428
+ slot: RenderPassInputSlot | RenderPassOutputSlot
1429
+ ): RenderTarget => {
1430
+ if (slot === 'source') {
1431
+ return slots.source;
1432
+ }
1433
+
1434
+ if (slot === 'target') {
1435
+ return slots.target;
1436
+ }
1437
+
1438
+ if (slot === 'canvas') {
1439
+ return slots.canvas;
1440
+ }
1441
+
1442
+ const named = runtimeTargets[slot];
1443
+ if (!named) {
1444
+ throw new Error(`Render graph references unknown runtime target "${slot}".`);
1445
+ }
1446
+
1447
+ return named;
1448
+ };
1449
+
1450
+ for (const step of graphPlan.steps) {
1451
+ const input = resolveStepSurface(step.input);
1452
+ const output = resolveStepSurface(step.output);
1453
+
1454
+ step.pass.render({
1455
+ device,
1456
+ commandEncoder,
1457
+ source: slots.source,
1458
+ target: slots.target,
1459
+ canvas: slots.canvas,
1460
+ input,
1461
+ output,
1462
+ targets: runtimeTargets,
1463
+ time,
1464
+ delta,
1465
+ width,
1466
+ height,
1467
+ clear: step.clear,
1468
+ clearColor: step.clearColor,
1469
+ preserve: step.preserve,
1470
+ beginRenderPass: (passOptions) => {
1471
+ const clear = passOptions?.clear ?? step.clear;
1472
+ const clearColor = passOptions?.clearColor ?? step.clearColor;
1473
+ const preserve = passOptions?.preserve ?? step.preserve;
1474
+
1475
+ return commandEncoder.beginRenderPass({
1476
+ colorAttachments: [
1477
+ {
1478
+ view: passOptions?.view ?? output.view,
1479
+ clearValue: {
1480
+ r: clearColor[0],
1481
+ g: clearColor[1],
1482
+ b: clearColor[2],
1483
+ a: clearColor[3]
1484
+ },
1485
+ loadOp: clear ? 'clear' : 'load',
1486
+ storeOp: preserve ? 'store' : 'discard'
1487
+ }
1488
+ ]
1489
+ });
1490
+ }
1491
+ });
1492
+
1493
+ if (step.needsSwap) {
1494
+ const previousSource = slots.source;
1495
+ slots.source = slots.target;
1496
+ slots.target = previousSource;
1497
+ }
1498
+ }
1499
+
1500
+ if (graphPlan.finalOutput !== 'canvas') {
1501
+ const finalSurface = resolveStepSurface(graphPlan.finalOutput);
1502
+ blitToCanvas(commandEncoder, finalSurface.view, slots.canvas.view, clearColor);
1503
+ }
1504
+ }
1505
+
1506
+ device.queue.submit([commandEncoder.finish()]);
1507
+ };
1508
+
1509
+ acceptInitializationCleanups = false;
1510
+ initializationCleanups.length = 0;
1511
+ return {
1512
+ render,
1513
+ destroy: () => {
1514
+ isDestroyed = true;
1515
+ device.removeEventListener('uncapturederror', handleUncapturedError);
1516
+ frameBuffer.destroy();
1517
+ uniformBuffer.destroy();
1518
+ destroyRenderTexture(sourceSlotTarget);
1519
+ destroyRenderTexture(targetSlotTarget);
1520
+ for (const target of runtimeRenderTargets.values()) {
1521
+ target.texture.destroy();
1522
+ }
1523
+ runtimeRenderTargets.clear();
1524
+ for (const pass of activePasses) {
1525
+ pass.dispose?.();
1526
+ }
1527
+ activePasses.length = 0;
1528
+ lifecyclePassesRef = null;
1529
+ for (const binding of textureBindings) {
1530
+ binding.texture?.destroy();
1531
+ binding.fallbackTexture.destroy();
1532
+ }
1533
+ blitBindGroupByView = new WeakMap();
1534
+ cachedGraphPlan = null;
1535
+ cachedGraphPasses.length = 0;
1536
+ renderTargetSnapshot = {};
1537
+ renderTargetKeys = [];
1538
+ }
1539
+ };
1540
+ } catch (error) {
1541
+ isDestroyed = true;
1542
+ acceptInitializationCleanups = false;
1543
+ device.removeEventListener('uncapturederror', handleUncapturedError);
1544
+ runInitializationCleanups();
1545
+ throw error;
1546
+ }
1547
+ }