@es3d/es3d 1.0.0 → 1.0.1

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 (79) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +86 -86
  3. package/docs/SPEC.md +417 -417
  4. package/package.json +1 -1
  5. package/scripts/es3d-cli.mjs +377 -377
  6. package/src/cache/geometry-store.js +392 -392
  7. package/src/cache/mesh-bundle.js +123 -123
  8. package/src/cache/sha256.js +73 -73
  9. package/src/format/ast.js +238 -238
  10. package/src/format/colors.js +93 -93
  11. package/src/format/compact-parser.js +171 -171
  12. package/src/format/compact-tokenizer.js +165 -165
  13. package/src/format/errors.js +247 -247
  14. package/src/format/json.js +55 -55
  15. package/src/format/limits.js +14 -14
  16. package/src/format/parse.js +92 -92
  17. package/src/format/schema.js +617 -617
  18. package/src/format/serializer.js +333 -333
  19. package/src/format/validator.js +330 -330
  20. package/src/format/value-error.js +12 -12
  21. package/src/format/value-format.js +314 -314
  22. package/src/format/values.js +459 -459
  23. package/src/format/xml-parser.js +136 -136
  24. package/src/format/xml-tokenizer.js +237 -237
  25. package/src/geometry/contour.js +86 -86
  26. package/src/geometry/extrude.js +175 -175
  27. package/src/geometry/gear.js +85 -85
  28. package/src/geometry/geometry-cache.js +159 -159
  29. package/src/geometry/lod-error.js +178 -178
  30. package/src/geometry/mesh.js +458 -458
  31. package/src/geometry/primitives.js +299 -299
  32. package/src/geometry/registry.js +645 -645
  33. package/src/geometry/revolve.js +136 -136
  34. package/src/geometry/sweep.js +441 -441
  35. package/src/index.js +47 -47
  36. package/src/io/compression.js +67 -67
  37. package/src/io/convert.js +236 -236
  38. package/src/io/download.js +13 -13
  39. package/src/io/external-scene.js +127 -127
  40. package/src/io/file-loader.js +28 -28
  41. package/src/io/gltf.js +630 -630
  42. package/src/io/mesh-import.js +104 -104
  43. package/src/io/obj.js +352 -352
  44. package/src/io/step-brep.js +439 -439
  45. package/src/io/step-exact.js +1149 -1149
  46. package/src/io/step.js +1418 -1418
  47. package/src/io/stl.js +193 -193
  48. package/src/io/svg-import.js +787 -787
  49. package/src/material/materials.js +154 -154
  50. package/src/math/mat4.js +475 -475
  51. package/src/math/random.js +30 -30
  52. package/src/math/trig.js +65 -65
  53. package/src/math/vec3.js +81 -81
  54. package/src/optimize/optimizer.js +579 -579
  55. package/src/path/path-flatten.js +322 -322
  56. package/src/path/path-parser.js +332 -332
  57. package/src/path/shapes.js +129 -129
  58. package/src/path/triangulate.js +517 -517
  59. package/src/pipeline.js +74 -74
  60. package/src/render/camera.js +168 -168
  61. package/src/render/frame-builder.js +362 -362
  62. package/src/render/geometry-pool.js +149 -149
  63. package/src/render/lighting.js +149 -149
  64. package/src/render/orbit-controls.js +237 -237
  65. package/src/render/renderer.js +258 -249
  66. package/src/render/scroll-timeline.js +104 -104
  67. package/src/render/shaders/glsl.js +285 -285
  68. package/src/render/shaders/wgsl.js +252 -252
  69. package/src/render/stage.js +364 -352
  70. package/src/render/texture-cache.js +40 -40
  71. package/src/render/textures.js +223 -223
  72. package/src/render/webgl2/webgl2-backend.js +586 -532
  73. package/src/render/webgpu/webgpu-backend.js +482 -480
  74. package/src/scene/flatten.js +754 -754
  75. package/src/scene/picking.js +161 -161
  76. package/src/scene/scene-graph.js +320 -320
  77. package/src/transform/transform.js +211 -211
  78. package/src/wasm/kernels-binary.js +3 -3
  79. package/src/wasm/kernels.js +385 -385
@@ -1,480 +1,482 @@
1
- // WebGPU rendering backend.
2
- //
3
- // Same architecture as the WebGL2 backend: one shared vertex buffer, one
4
- // shared uint32 index buffer, one instance buffer, explicit bind group
5
- // layouts and a cache of pipeline variants (shader specialised per material
6
- // features and light setup, cull mode, winding, blending, topology). Each
7
- // batch is one drawIndexed call using firstInstance.
8
-
9
- import { meshShader, LINE_WGSL } from '../shaders/wgsl.js';
10
- import { FRAME_BYTES, MATERIAL_FLOATS, packMaterial, packOverlay, lightTypes } from '../lighting.js';
11
- import { VERTEX_BYTES } from '../geometry-pool.js';
12
- import { buildMips } from '../textures.js';
13
-
14
- const SAMPLE_COUNT = 4;
15
-
16
- const VERTEX_LAYOUTS = [
17
- {
18
- arrayStride: VERTEX_BYTES,
19
- stepMode: 'vertex',
20
- attributes: [
21
- { shaderLocation: 0, offset: 0, format: 'float32x3' },
22
- { shaderLocation: 1, offset: 12, format: 'float32x3' },
23
- { shaderLocation: 2, offset: 24, format: 'float32x2' },
24
- ],
25
- },
26
- {
27
- arrayStride: 64,
28
- stepMode: 'instance',
29
- attributes: [
30
- { shaderLocation: 3, offset: 0, format: 'float32x4' },
31
- { shaderLocation: 4, offset: 16, format: 'float32x4' },
32
- { shaderLocation: 5, offset: 32, format: 'float32x4' },
33
- { shaderLocation: 6, offset: 48, format: 'float32x4' },
34
- ],
35
- },
36
- ];
37
-
38
- const pow2 = (n, min) => {
39
- let c = min;
40
- while (c < n) c *= 2;
41
- return c;
42
- };
43
-
44
- export class WebGPUBackend {
45
- /**
46
- * @param {HTMLCanvasElement} canvas
47
- * @param {{present?: 'canvas'|'readback'}} [opts] 'readback' renders offscreen and
48
- * copies pixels into a 2D canvas (headless testing, screenshots without a swap chain)
49
- */
50
- constructor(canvas, opts = {}) {
51
- this.canvas = canvas;
52
- this.present = opts.present || 'canvas';
53
- this.kind = 'webgpu';
54
- this.zeroToOne = true;
55
- this.pipelines = new Map();
56
- this.meshModules = new Map();
57
- this.materialBindings = new Map();
58
- this.overlayBindings = new Map();
59
- this.poolGeneration = -1;
60
- this.vertexBuffer = null;
61
- this.indexBuffer = null;
62
- this.instanceBuffer = null;
63
- this.gpuBytes = 0;
64
- this.lost = false;
65
- this.info = '';
66
- this.errors = [];
67
- }
68
-
69
- async init() {
70
- if (!navigator.gpu) throw new Error('WebGPU is not available in this browser.');
71
- const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
72
- if (!adapter) throw new Error('No WebGPU adapter is available.');
73
- this.adapter = adapter;
74
- const info = adapter.info || {};
75
- this.info = [info.vendor, info.architecture, info.description].filter(Boolean).join(' ') || 'WebGPU adapter';
76
- const device = await adapter.requestDevice();
77
- this.device = device;
78
- device.lost.then((i) => {
79
- this.lost = true;
80
- this.errors.push(`WebGPU device lost: ${i.message}`);
81
- });
82
- device.onuncapturederror = (e) => {
83
- this.errors.push(e.error && e.error.message ? e.error.message : String(e));
84
- };
85
- if (this.present === 'readback') {
86
- this.format = 'rgba8unorm';
87
- this.ctx2d = this.canvas.getContext('2d');
88
- if (!this.ctx2d) throw new Error('Cannot create a 2D context for WebGPU readback presentation.');
89
- } else {
90
- const ctx = this.canvas.getContext('webgpu');
91
- if (!ctx) throw new Error('Cannot create a WebGPU canvas context.');
92
- this.context = ctx;
93
- this.format = navigator.gpu.getPreferredCanvasFormat();
94
- // colours are written already encoded as sRGB and tone mapped to 0..1: pin the
95
- // colour space and standard range so HDR and wide-gamut screens show them unchanged
96
- ctx.configure({ device, format: this.format, alphaMode: 'opaque', colorSpace: 'srgb', toneMapping: { mode: 'standard' } });
97
- }
98
-
99
- this.frameLayout = device.createBindGroupLayout({
100
- entries: [{ binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }],
101
- });
102
- this.materialLayout = device.createBindGroupLayout({
103
- entries: [
104
- { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } },
105
- { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } },
106
- { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
107
- { binding: 3, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
108
- { binding: 4, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
109
- { binding: 5, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
110
- { binding: 6, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
111
- ],
112
- });
113
- this.pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [this.frameLayout, this.materialLayout] });
114
- device.pushErrorScope('validation');
115
- this.lineModule = device.createShaderModule({ code: LINE_WGSL, label: 'es3d lines' });
116
- for (const [name, mod] of [['mesh', this.meshModule(0, '0')], ['lines', this.lineModule]]) {
117
- const info2 = await mod.getCompilationInfo();
118
- const errs = info2.messages.filter((m) => m.type === 'error');
119
- if (errs.length) throw new Error(`WGSL ${name} shader error: ${errs.map((m) => `${m.lineNum}:${m.linePos} ${m.message}`).join('; ')}`);
120
- }
121
- const err = await device.popErrorScope();
122
- if (err) throw new Error(`WebGPU initialisation error: ${err.message}`);
123
-
124
- this.frameBuffer = device.createBuffer({ size: FRAME_BYTES, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
125
- this.frameBindGroup = device.createBindGroup({ layout: this.frameLayout, entries: [{ binding: 0, resource: { buffer: this.frameBuffer } }] });
126
- this.sampler = device.createSampler({
127
- addressModeU: 'repeat',
128
- addressModeV: 'repeat',
129
- magFilter: 'linear',
130
- minFilter: 'linear',
131
- mipmapFilter: 'linear',
132
- maxAnisotropy: 8,
133
- });
134
- this.whiteTex = this.createTexture({ width: 1, height: 1, data: new Uint8Array([255, 255, 255, 255]) }, true);
135
- this.flatNormalTex = this.createTexture({ width: 1, height: 1, data: new Uint8Array([128, 128, 255, 255]) }, false);
136
- this.matData = new Float32Array(MATERIAL_FLOATS);
137
- }
138
-
139
- createTexture(px, srgb) {
140
- const levels = px.width > 1 || px.height > 1 ? buildMips(px) : [px];
141
- const tex = this.device.createTexture({
142
- size: [px.width, px.height],
143
- format: srgb ? 'rgba8unorm-srgb' : 'rgba8unorm',
144
- mipLevelCount: levels.length,
145
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
146
- });
147
- levels.forEach((lv, i) => {
148
- const data = lv.data instanceof Uint8Array ? lv.data : new Uint8Array(lv.data.buffer, lv.data.byteOffset, lv.data.byteLength);
149
- this.device.queue.writeTexture({ texture: tex, mipLevel: i }, data, { bytesPerRow: lv.width * 4, rowsPerImage: lv.height }, [lv.width, lv.height]);
150
- this.gpuBytes += lv.width * lv.height * 4;
151
- });
152
- return { texture: tex, view: tex.createView() };
153
- }
154
-
155
- destroyTexture(t) {
156
- t.texture.destroy();
157
- }
158
-
159
- /** The shader module for a material's feature flags under the frame's lights, compiled on first use. */
160
- meshModule(flags, lights) {
161
- const key = `${flags}|${lights}`;
162
- let m = this.meshModules.get(key);
163
- if (!m) {
164
- m = this.device.createShaderModule({ code: meshShader(flags, lights), label: `es3d mesh ${key}` });
165
- this.meshModules.set(key, m);
166
- }
167
- return m;
168
- }
169
-
170
- pipeline(kind, { cull = 'back', frontFace = 'ccw', blend = false, depthWrite = true, depthCompare = 'less-equal', flags = 0, lights = '' } = {}) {
171
- const isMesh = kind === 'mesh';
172
- const key = `${kind}|${cull}|${frontFace}|${blend}|${depthWrite}|${depthCompare}${isMesh ? `|${flags}|${lights}` : ''}`;
173
- let p = this.pipelines.get(key);
174
- if (p) return p;
175
- const module = isMesh ? this.meshModule(flags, lights) : this.lineModule;
176
- const entry = isMesh ? 'vs_main' : kind === 'normals' ? 'vs_normals' : 'vs_line';
177
- p = this.device.createRenderPipeline({
178
- label: key,
179
- layout: this.pipelineLayout,
180
- vertex: { module, entryPoint: entry, buffers: VERTEX_LAYOUTS },
181
- fragment: {
182
- module,
183
- entryPoint: isMesh ? 'fs_main' : 'fs_line',
184
- targets: [
185
- {
186
- format: this.format,
187
- blend: blend
188
- ? {
189
- color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' },
190
- alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },
191
- }
192
- : undefined,
193
- },
194
- ],
195
- },
196
- primitive: { topology: isMesh ? 'triangle-list' : 'line-list', cullMode: isMesh ? cull : 'none', frontFace },
197
- depthStencil: { format: 'depth24plus', depthWriteEnabled: depthWrite, depthCompare },
198
- multisample: { count: SAMPLE_COUNT },
199
- });
200
- this.pipelines.set(key, p);
201
- return p;
202
- }
203
-
204
- ensureTargets() {
205
- const w = this.canvas.width, h = this.canvas.height;
206
- if (this.targetW === w && this.targetH === h && this.msaa) return;
207
- if (this.msaa) this.msaa.destroy();
208
- if (this.depth) this.depth.destroy();
209
- this.msaa = this.device.createTexture({ size: [w, h], sampleCount: SAMPLE_COUNT, format: this.format, usage: GPUTextureUsage.RENDER_ATTACHMENT });
210
- this.depth = this.device.createTexture({ size: [w, h], sampleCount: SAMPLE_COUNT, format: 'depth24plus', usage: GPUTextureUsage.RENDER_ATTACHMENT });
211
- this.msaaView = this.msaa.createView();
212
- this.depthView = this.depth.createView();
213
- if (this.present === 'readback') {
214
- if (this.offscreen) this.offscreen.destroy();
215
- if (this.readBuffer && !this.readPending) this.readBuffer.destroy();
216
- this.offscreen = this.device.createTexture({ size: [w, h], format: this.format, usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC });
217
- this.offscreenView = this.offscreen.createView();
218
- this.readStride = Math.ceil((w * 4) / 256) * 256;
219
- this.readBuffer = this.device.createBuffer({ size: this.readStride * h, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
220
- }
221
- this.targetW = w;
222
- this.targetH = h;
223
- }
224
-
225
- /** Copy the offscreen frame into the 2D canvas (readback presentation). */
226
- readback(encoder) {
227
- if (this.readPending) return false;
228
- const w = this.targetW, h = this.targetH;
229
- encoder.copyTextureToBuffer({ texture: this.offscreen }, { buffer: this.readBuffer, bytesPerRow: this.readStride }, [w, h]);
230
- return true;
231
- }
232
-
233
- startReadback() {
234
- const buf = this.readBuffer;
235
- const w = this.targetW, h = this.targetH, stride = this.readStride;
236
- this.readPending = buf.mapAsync(GPUMapMode.READ).then(() => {
237
- const raw = new Uint8Array(buf.getMappedRange());
238
- const px = new Uint8ClampedArray(w * h * 4);
239
- for (let y = 0; y < h; y++) px.set(raw.subarray(y * stride, y * stride + w * 4), y * w * 4);
240
- buf.unmap();
241
- this.ctx2d.putImageData(new ImageData(px, w, h), 0, 0);
242
- this.readPending = null;
243
- // A frame drawn while this copy was in flight was not copied. A page that
244
- // draws only on change may draw nothing more, so show that frame now.
245
- if (!this.lastFrameCopied && this.offscreen && !this.lost) {
246
- const encoder = this.device.createCommandEncoder();
247
- this.readback(encoder);
248
- this.device.queue.submit([encoder.finish()]);
249
- this.lastFrameCopied = true;
250
- this.startReadback();
251
- }
252
- });
253
- }
254
-
255
- syncPool(pool) {
256
- const d = this.device;
257
- const vBytes = pool.vertices.byteLength;
258
- const iBytes = pool.indices.byteLength;
259
- let uploaded = 0;
260
- if (pool.generation !== this.poolGeneration || !this.vertexBuffer || this.vertexBuffer.size < vBytes || this.indexBuffer.size < iBytes) {
261
- if (this.vertexBuffer) this.vertexBuffer.destroy();
262
- if (this.indexBuffer) this.indexBuffer.destroy();
263
- this.vertexBuffer = d.createBuffer({ size: pow2(vBytes, 1 << 16), usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
264
- this.indexBuffer = d.createBuffer({ size: pow2(iBytes, 1 << 16), usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });
265
- this.poolGeneration = pool.generation;
266
- pool.uploadedVertices = 0;
267
- pool.uploadedIndices = 0;
268
- }
269
- const p = pool.pending();
270
- if (p.vertexEnd > p.vertexStart) {
271
- const src = pool.vertices.subarray(p.vertexStart * 8, p.vertexEnd * 8);
272
- d.queue.writeBuffer(this.vertexBuffer, p.vertexStart * VERTEX_BYTES, src.buffer, src.byteOffset, src.byteLength);
273
- uploaded += src.byteLength;
274
- }
275
- if (p.indexEnd > p.indexStart) {
276
- const src = pool.indices.subarray(p.indexStart, p.indexEnd);
277
- d.queue.writeBuffer(this.indexBuffer, p.indexStart * 4, src.buffer, src.byteOffset, src.byteLength);
278
- uploaded += src.byteLength;
279
- }
280
- pool.markUploaded();
281
- return uploaded;
282
- }
283
-
284
- uploadInstances(data, count) {
285
- const bytes = Math.max(64, count * 64);
286
- if (!this.instanceBuffer || this.instanceBuffer.size < bytes) {
287
- if (this.instanceBuffer) this.instanceBuffer.destroy();
288
- this.instanceBuffer = this.device.createBuffer({ size: pow2(bytes, 64 * 256), usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
289
- }
290
- if (count) this.device.queue.writeBuffer(this.instanceBuffer, 0, data.buffer, data.byteOffset, count * 64);
291
- return count * 64;
292
- }
293
-
294
- readyTexture(entry, srgb) {
295
- if (entry && entry.status === 'ready' && !entry.gpu) entry.gpu = this.createTexture(entry.pixels, srgb);
296
- return entry && entry.gpu ? entry.gpu : null;
297
- }
298
-
299
- materialEntries(buffer, map, normal, mr, occlusion, emissive) {
300
- return [
301
- { binding: 0, resource: { buffer } },
302
- { binding: 1, resource: this.sampler },
303
- { binding: 2, resource: map.view },
304
- { binding: 3, resource: normal.view },
305
- { binding: 4, resource: mr.view },
306
- { binding: 5, resource: occlusion.view },
307
- { binding: 6, resource: emissive.view },
308
- ];
309
- }
310
-
311
- materialBinding(material, textures, doubleSided) {
312
- const id = doubleSided ? 'ds' : 'ss';
313
- let rec = this.materialBindings.get(material);
314
- if (!rec) {
315
- rec = {};
316
- this.materialBindings.set(material, rec);
317
- }
318
- const mapGpu = this.readyTexture(material.map ? textures.get(material.map, 'color') : null, true);
319
- const nrmGpu = this.readyTexture(material.normalMap ? textures.get(material.normalMap, 'normal') : null, false);
320
- const mrGpu = this.readyTexture(material.metallicRoughnessMap ? textures.get(material.metallicRoughnessMap, 'linear') : null, false);
321
- const occGpu = this.readyTexture(material.occlusionMap ? textures.get(material.occlusionMap, 'linear') : null, false);
322
- const emGpu = this.readyTexture(material.emissiveMap ? textures.get(material.emissiveMap, 'color') : null, true);
323
- const hasMap = !!mapGpu;
324
- const hasNormalMap = !!nrmGpu;
325
- const hasMrMap = !!mrGpu;
326
- const hasOcclusionMap = !!occGpu;
327
- const hasEmissiveMap = !!emGpu;
328
- const key = `${hasMap}|${hasNormalMap}|${hasMrMap}|${hasOcclusionMap}|${hasEmissiveMap}`;
329
- let b = rec[id];
330
- if (!b || b.key !== key) {
331
- if (b) b.buffer.destroy();
332
- packMaterial(this.matData, material, { hasMap, hasNormalMap, hasMrMap, hasOcclusionMap, hasEmissiveMap, doubleSided: doubleSided || material.doubleSided });
333
- const buffer = this.device.createBuffer({ size: MATERIAL_FLOATS * 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
334
- this.device.queue.writeBuffer(buffer, 0, this.matData);
335
- const bindGroup = this.device.createBindGroup({
336
- layout: this.materialLayout,
337
- entries: this.materialEntries(buffer, mapGpu || this.whiteTex, nrmGpu || this.flatNormalTex, mrGpu || this.whiteTex, occGpu || this.whiteTex, emGpu || this.whiteTex),
338
- });
339
- b = rec[id] = { key, buffer, bindGroup, flags: this.matData[10] };
340
- }
341
- return b;
342
- }
343
-
344
- overlayBinding(name, rgba) {
345
- let b = this.overlayBindings.get(name);
346
- if (b) return b;
347
- packOverlay(this.matData, rgba);
348
- const buffer = this.device.createBuffer({ size: MATERIAL_FLOATS * 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
349
- this.device.queue.writeBuffer(buffer, 0, this.matData);
350
- b = this.device.createBindGroup({
351
- layout: this.materialLayout,
352
- entries: this.materialEntries(buffer, this.whiteTex, this.flatNormalTex, this.whiteTex, this.whiteTex, this.whiteTex),
353
- });
354
- this.overlayBindings.set(name, b);
355
- return b;
356
- }
357
-
358
- releaseMaterials(keep) {
359
- for (const [m, rec] of this.materialBindings) {
360
- if (keep.has(m)) continue;
361
- for (const b of Object.values(rec)) b.buffer.destroy();
362
- this.materialBindings.delete(m);
363
- }
364
- }
365
-
366
- /** What this backend renders with (Renderer.caps). */
367
- get caps() {
368
- return {
369
- msaaSamples: SAMPLE_COUNT,
370
- anisotropy: 8,
371
- maxTextureSize: this.device ? this.device.limits.maxTextureDimension2D : 0,
372
- colorSpace: 'srgb',
373
- };
374
- }
375
-
376
- resize(width, height) {
377
- if (this.canvas.width !== width || this.canvas.height !== height) {
378
- this.canvas.width = width;
379
- this.canvas.height = height;
380
- }
381
- }
382
-
383
- render(draw, frameData, ctx) {
384
- if (this.lost) return;
385
- const d = this.device;
386
- this.ensureTargets();
387
- d.queue.writeBuffer(this.frameBuffer, 0, frameData.buffer, frameData.byteOffset, frameData.byteLength);
388
- this.uploadInstances(draw.instanceData, draw.instanceCount);
389
- const encoder = d.createCommandEncoder();
390
- const pass = encoder.beginRenderPass({
391
- colorAttachments: [
392
- {
393
- view: this.msaaView,
394
- resolveTarget: this.present === 'readback' ? this.offscreenView : this.context.getCurrentTexture().createView(),
395
- clearValue: { r: ctx.background[0], g: ctx.background[1], b: ctx.background[2], a: 1 },
396
- loadOp: 'clear',
397
- storeOp: 'discard',
398
- },
399
- ],
400
- depthStencilAttachment: { view: this.depthView, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'discard' },
401
- });
402
- pass.setBindGroup(0, this.frameBindGroup);
403
- if (this.vertexBuffer) {
404
- pass.setVertexBuffer(0, this.vertexBuffer);
405
- pass.setIndexBuffer(this.indexBuffer, 'uint32');
406
- }
407
- pass.setVertexBuffer(1, this.instanceBuffer);
408
- let currentPipeline = null;
409
- const setPipe = (p) => {
410
- if (p !== currentPipeline) {
411
- pass.setPipeline(p);
412
- currentPipeline = p;
413
- }
414
- };
415
- if (this.vertexBuffer) {
416
- let boundGroup = null;
417
- const lights = lightTypes(frameData);
418
- for (const b of draw.batches) {
419
- const lines = b.kind === 'lines';
420
- const binding = this.materialBinding(b.material, ctx.textures, b.doubleSided && !b.material.doubleSided);
421
- const pipe = lines
422
- ? this.pipeline('lines', { blend: b.transparent, depthWrite: !b.transparent })
423
- : this.pipeline('mesh', {
424
- cull: b.doubleSided ? 'none' : 'back',
425
- frontFace: b.mirrored ? 'cw' : 'ccw',
426
- blend: b.transparent,
427
- depthWrite: !b.transparent,
428
- flags: binding.flags,
429
- lights,
430
- });
431
- setPipe(pipe);
432
- const group = binding.bindGroup;
433
- if (group !== boundGroup) {
434
- pass.setBindGroup(1, group);
435
- boundGroup = group;
436
- }
437
- pass.drawIndexed(b.range.indexCount, b.count, b.range.firstIndex, 0, b.firstInstance);
438
- }
439
- const ov = draw.overlays;
440
- const drawLines = (kind, name, color, list, depthCompare = 'less-equal') => {
441
- if (!list.length) return;
442
- setPipe(this.pipeline(kind, { blend: true, depthWrite: false, depthCompare }));
443
- pass.setBindGroup(1, this.overlayBinding(name, color));
444
- for (const o of list) pass.drawIndexed(o.range.indexCount, o.count, o.range.firstIndex, 0, o.firstInstance);
445
- };
446
- drawLines('lines', 'wireframe', ctx.overlayColors.wireframe, ov.wireframe);
447
- drawLines('normals', 'normals', ctx.overlayColors.normals, ov.normals);
448
- if (ov.bbox && ov.bbox.count) drawLines('lines', 'bbox', ctx.overlayColors.bbox, [{ ...ov.bbox, range: ctx.cubeRange }]);
449
- if (ov.selection && ov.selection.count) drawLines('lines', 'selection', ctx.overlayColors.selection, [{ ...ov.selection, range: ctx.cubeRange }], 'always');
450
- }
451
- pass.end();
452
- const copied = this.present === 'readback' && this.readback(encoder);
453
- d.queue.submit([encoder.finish()]);
454
- if (copied) this.startReadback();
455
- this.lastFrameCopied = copied;
456
- }
457
-
458
- async finish() {
459
- await this.device.queue.onSubmittedWorkDone();
460
- if (this.readPending) await this.readPending;
461
- if (this.present === 'readback' && !this.lastFrameCopied && this.offscreen) {
462
- // the latest frame was rendered while an older readback was in flight
463
- const encoder = this.device.createCommandEncoder();
464
- this.readback(encoder);
465
- this.device.queue.submit([encoder.finish()]);
466
- this.startReadback();
467
- await this.readPending;
468
- this.lastFrameCopied = true;
469
- }
470
- }
471
-
472
- dispose() {
473
- if (!this.device) return;
474
- for (const b of [this.vertexBuffer, this.indexBuffer, this.instanceBuffer, this.frameBuffer]) if (b) b.destroy();
475
- for (const rec of this.materialBindings.values()) for (const b of Object.values(rec)) b.buffer.destroy();
476
- if (this.msaa) this.msaa.destroy();
477
- if (this.depth) this.depth.destroy();
478
- this.device.destroy();
479
- }
480
- }
1
+ // WebGPU rendering backend.
2
+ //
3
+ // Same architecture as the WebGL2 backend: one shared vertex buffer, one
4
+ // shared uint32 index buffer, one instance buffer, explicit bind group
5
+ // layouts and a cache of pipeline variants (shader specialised per material
6
+ // features and light setup, cull mode, winding, blending, topology). Each
7
+ // batch is one drawIndexed call using firstInstance.
8
+
9
+ import { meshShader, LINE_WGSL } from '../shaders/wgsl.js';
10
+ import { FRAME_BYTES, MATERIAL_FLOATS, packMaterial, packOverlay, lightTypes } from '../lighting.js';
11
+ import { VERTEX_BYTES } from '../geometry-pool.js';
12
+ import { buildMips } from '../textures.js';
13
+
14
+ const SAMPLE_COUNT = 4;
15
+
16
+ const VERTEX_LAYOUTS = [
17
+ {
18
+ arrayStride: VERTEX_BYTES,
19
+ stepMode: 'vertex',
20
+ attributes: [
21
+ { shaderLocation: 0, offset: 0, format: 'float32x3' },
22
+ { shaderLocation: 1, offset: 12, format: 'float32x3' },
23
+ { shaderLocation: 2, offset: 24, format: 'float32x2' },
24
+ ],
25
+ },
26
+ {
27
+ arrayStride: 64,
28
+ stepMode: 'instance',
29
+ attributes: [
30
+ { shaderLocation: 3, offset: 0, format: 'float32x4' },
31
+ { shaderLocation: 4, offset: 16, format: 'float32x4' },
32
+ { shaderLocation: 5, offset: 32, format: 'float32x4' },
33
+ { shaderLocation: 6, offset: 48, format: 'float32x4' },
34
+ ],
35
+ },
36
+ ];
37
+
38
+ const pow2 = (n, min) => {
39
+ let c = min;
40
+ while (c < n) c *= 2;
41
+ return c;
42
+ };
43
+
44
+ export class WebGPUBackend {
45
+ /**
46
+ * @param {HTMLCanvasElement} canvas
47
+ * @param {{present?: 'canvas'|'readback'}} [opts] 'readback' renders offscreen and
48
+ * copies pixels into a 2D canvas (headless testing, screenshots without a swap chain)
49
+ */
50
+ constructor(canvas, opts = {}) {
51
+ this.canvas = canvas;
52
+ this.present = opts.present || 'canvas';
53
+ this.kind = 'webgpu';
54
+ this.zeroToOne = true;
55
+ this.pipelines = new Map();
56
+ this.meshModules = new Map();
57
+ this.materialBindings = new Map();
58
+ this.overlayBindings = new Map();
59
+ this.poolGeneration = -1;
60
+ this.vertexBuffer = null;
61
+ this.indexBuffer = null;
62
+ this.instanceBuffer = null;
63
+ this.gpuBytes = 0;
64
+ this.lost = false;
65
+ this.info = '';
66
+ this.errors = [];
67
+ }
68
+
69
+ async init() {
70
+ if (!navigator.gpu) throw new Error('WebGPU is not available in this browser.');
71
+ const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
72
+ if (!adapter) throw new Error('No WebGPU adapter is available.');
73
+ this.adapter = adapter;
74
+ const info = adapter.info || {};
75
+ this.info = [info.vendor, info.architecture, info.description].filter(Boolean).join(' ') || 'WebGPU adapter';
76
+ const device = await adapter.requestDevice();
77
+ this.device = device;
78
+ device.lost.then((i) => {
79
+ this.lost = true;
80
+ this.errors.push(`WebGPU device lost: ${i.message}`);
81
+ });
82
+ device.onuncapturederror = (e) => {
83
+ this.errors.push(e.error && e.error.message ? e.error.message : String(e));
84
+ };
85
+ if (this.present === 'readback') {
86
+ this.format = 'rgba8unorm';
87
+ this.ctx2d = this.canvas.getContext('2d');
88
+ if (!this.ctx2d) throw new Error('Cannot create a 2D context for WebGPU readback presentation.');
89
+ this.canvasUsed = true;
90
+ } else {
91
+ const ctx = this.canvas.getContext('webgpu');
92
+ if (!ctx) throw new Error('Cannot create a WebGPU canvas context.');
93
+ this.canvasUsed = true;
94
+ this.context = ctx;
95
+ this.format = navigator.gpu.getPreferredCanvasFormat();
96
+ // colours are written already encoded as sRGB and tone mapped to 0..1: pin the
97
+ // colour space and standard range so HDR and wide-gamut screens show them unchanged
98
+ ctx.configure({ device, format: this.format, alphaMode: 'opaque', colorSpace: 'srgb', toneMapping: { mode: 'standard' } });
99
+ }
100
+
101
+ this.frameLayout = device.createBindGroupLayout({
102
+ entries: [{ binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }],
103
+ });
104
+ this.materialLayout = device.createBindGroupLayout({
105
+ entries: [
106
+ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } },
107
+ { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } },
108
+ { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
109
+ { binding: 3, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
110
+ { binding: 4, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
111
+ { binding: 5, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
112
+ { binding: 6, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },
113
+ ],
114
+ });
115
+ this.pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [this.frameLayout, this.materialLayout] });
116
+ device.pushErrorScope('validation');
117
+ this.lineModule = device.createShaderModule({ code: LINE_WGSL, label: 'es3d lines' });
118
+ for (const [name, mod] of [['mesh', this.meshModule(0, '0')], ['lines', this.lineModule]]) {
119
+ const info2 = await mod.getCompilationInfo();
120
+ const errs = info2.messages.filter((m) => m.type === 'error');
121
+ if (errs.length) throw new Error(`WGSL ${name} shader error: ${errs.map((m) => `${m.lineNum}:${m.linePos} ${m.message}`).join('; ')}`);
122
+ }
123
+ const err = await device.popErrorScope();
124
+ if (err) throw new Error(`WebGPU initialisation error: ${err.message}`);
125
+
126
+ this.frameBuffer = device.createBuffer({ size: FRAME_BYTES, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
127
+ this.frameBindGroup = device.createBindGroup({ layout: this.frameLayout, entries: [{ binding: 0, resource: { buffer: this.frameBuffer } }] });
128
+ this.sampler = device.createSampler({
129
+ addressModeU: 'repeat',
130
+ addressModeV: 'repeat',
131
+ magFilter: 'linear',
132
+ minFilter: 'linear',
133
+ mipmapFilter: 'linear',
134
+ maxAnisotropy: 8,
135
+ });
136
+ this.whiteTex = this.createTexture({ width: 1, height: 1, data: new Uint8Array([255, 255, 255, 255]) }, true);
137
+ this.flatNormalTex = this.createTexture({ width: 1, height: 1, data: new Uint8Array([128, 128, 255, 255]) }, false);
138
+ this.matData = new Float32Array(MATERIAL_FLOATS);
139
+ }
140
+
141
+ createTexture(px, srgb) {
142
+ const levels = px.width > 1 || px.height > 1 ? buildMips(px) : [px];
143
+ const tex = this.device.createTexture({
144
+ size: [px.width, px.height],
145
+ format: srgb ? 'rgba8unorm-srgb' : 'rgba8unorm',
146
+ mipLevelCount: levels.length,
147
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
148
+ });
149
+ levels.forEach((lv, i) => {
150
+ const data = lv.data instanceof Uint8Array ? lv.data : new Uint8Array(lv.data.buffer, lv.data.byteOffset, lv.data.byteLength);
151
+ this.device.queue.writeTexture({ texture: tex, mipLevel: i }, data, { bytesPerRow: lv.width * 4, rowsPerImage: lv.height }, [lv.width, lv.height]);
152
+ this.gpuBytes += lv.width * lv.height * 4;
153
+ });
154
+ return { texture: tex, view: tex.createView() };
155
+ }
156
+
157
+ destroyTexture(t) {
158
+ t.texture.destroy();
159
+ }
160
+
161
+ /** The shader module for a material's feature flags under the frame's lights, compiled on first use. */
162
+ meshModule(flags, lights) {
163
+ const key = `${flags}|${lights}`;
164
+ let m = this.meshModules.get(key);
165
+ if (!m) {
166
+ m = this.device.createShaderModule({ code: meshShader(flags, lights), label: `es3d mesh ${key}` });
167
+ this.meshModules.set(key, m);
168
+ }
169
+ return m;
170
+ }
171
+
172
+ pipeline(kind, { cull = 'back', frontFace = 'ccw', blend = false, depthWrite = true, depthCompare = 'less-equal', flags = 0, lights = '' } = {}) {
173
+ const isMesh = kind === 'mesh';
174
+ const key = `${kind}|${cull}|${frontFace}|${blend}|${depthWrite}|${depthCompare}${isMesh ? `|${flags}|${lights}` : ''}`;
175
+ let p = this.pipelines.get(key);
176
+ if (p) return p;
177
+ const module = isMesh ? this.meshModule(flags, lights) : this.lineModule;
178
+ const entry = isMesh ? 'vs_main' : kind === 'normals' ? 'vs_normals' : 'vs_line';
179
+ p = this.device.createRenderPipeline({
180
+ label: key,
181
+ layout: this.pipelineLayout,
182
+ vertex: { module, entryPoint: entry, buffers: VERTEX_LAYOUTS },
183
+ fragment: {
184
+ module,
185
+ entryPoint: isMesh ? 'fs_main' : 'fs_line',
186
+ targets: [
187
+ {
188
+ format: this.format,
189
+ blend: blend
190
+ ? {
191
+ color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' },
192
+ alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },
193
+ }
194
+ : undefined,
195
+ },
196
+ ],
197
+ },
198
+ primitive: { topology: isMesh ? 'triangle-list' : 'line-list', cullMode: isMesh ? cull : 'none', frontFace },
199
+ depthStencil: { format: 'depth24plus', depthWriteEnabled: depthWrite, depthCompare },
200
+ multisample: { count: SAMPLE_COUNT },
201
+ });
202
+ this.pipelines.set(key, p);
203
+ return p;
204
+ }
205
+
206
+ ensureTargets() {
207
+ const w = this.canvas.width, h = this.canvas.height;
208
+ if (this.targetW === w && this.targetH === h && this.msaa) return;
209
+ if (this.msaa) this.msaa.destroy();
210
+ if (this.depth) this.depth.destroy();
211
+ this.msaa = this.device.createTexture({ size: [w, h], sampleCount: SAMPLE_COUNT, format: this.format, usage: GPUTextureUsage.RENDER_ATTACHMENT });
212
+ this.depth = this.device.createTexture({ size: [w, h], sampleCount: SAMPLE_COUNT, format: 'depth24plus', usage: GPUTextureUsage.RENDER_ATTACHMENT });
213
+ this.msaaView = this.msaa.createView();
214
+ this.depthView = this.depth.createView();
215
+ if (this.present === 'readback') {
216
+ if (this.offscreen) this.offscreen.destroy();
217
+ if (this.readBuffer && !this.readPending) this.readBuffer.destroy();
218
+ this.offscreen = this.device.createTexture({ size: [w, h], format: this.format, usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC });
219
+ this.offscreenView = this.offscreen.createView();
220
+ this.readStride = Math.ceil((w * 4) / 256) * 256;
221
+ this.readBuffer = this.device.createBuffer({ size: this.readStride * h, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
222
+ }
223
+ this.targetW = w;
224
+ this.targetH = h;
225
+ }
226
+
227
+ /** Copy the offscreen frame into the 2D canvas (readback presentation). */
228
+ readback(encoder) {
229
+ if (this.readPending) return false;
230
+ const w = this.targetW, h = this.targetH;
231
+ encoder.copyTextureToBuffer({ texture: this.offscreen }, { buffer: this.readBuffer, bytesPerRow: this.readStride }, [w, h]);
232
+ return true;
233
+ }
234
+
235
+ startReadback() {
236
+ const buf = this.readBuffer;
237
+ const w = this.targetW, h = this.targetH, stride = this.readStride;
238
+ this.readPending = buf.mapAsync(GPUMapMode.READ).then(() => {
239
+ const raw = new Uint8Array(buf.getMappedRange());
240
+ const px = new Uint8ClampedArray(w * h * 4);
241
+ for (let y = 0; y < h; y++) px.set(raw.subarray(y * stride, y * stride + w * 4), y * w * 4);
242
+ buf.unmap();
243
+ this.ctx2d.putImageData(new ImageData(px, w, h), 0, 0);
244
+ this.readPending = null;
245
+ // A frame drawn while this copy was in flight was not copied. A page that
246
+ // draws only on change may draw nothing more, so show that frame now.
247
+ if (!this.lastFrameCopied && this.offscreen && !this.lost) {
248
+ const encoder = this.device.createCommandEncoder();
249
+ this.readback(encoder);
250
+ this.device.queue.submit([encoder.finish()]);
251
+ this.lastFrameCopied = true;
252
+ this.startReadback();
253
+ }
254
+ });
255
+ }
256
+
257
+ syncPool(pool) {
258
+ const d = this.device;
259
+ const vBytes = pool.vertices.byteLength;
260
+ const iBytes = pool.indices.byteLength;
261
+ let uploaded = 0;
262
+ if (pool.generation !== this.poolGeneration || !this.vertexBuffer || this.vertexBuffer.size < vBytes || this.indexBuffer.size < iBytes) {
263
+ if (this.vertexBuffer) this.vertexBuffer.destroy();
264
+ if (this.indexBuffer) this.indexBuffer.destroy();
265
+ this.vertexBuffer = d.createBuffer({ size: pow2(vBytes, 1 << 16), usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
266
+ this.indexBuffer = d.createBuffer({ size: pow2(iBytes, 1 << 16), usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });
267
+ this.poolGeneration = pool.generation;
268
+ pool.uploadedVertices = 0;
269
+ pool.uploadedIndices = 0;
270
+ }
271
+ const p = pool.pending();
272
+ if (p.vertexEnd > p.vertexStart) {
273
+ const src = pool.vertices.subarray(p.vertexStart * 8, p.vertexEnd * 8);
274
+ d.queue.writeBuffer(this.vertexBuffer, p.vertexStart * VERTEX_BYTES, src.buffer, src.byteOffset, src.byteLength);
275
+ uploaded += src.byteLength;
276
+ }
277
+ if (p.indexEnd > p.indexStart) {
278
+ const src = pool.indices.subarray(p.indexStart, p.indexEnd);
279
+ d.queue.writeBuffer(this.indexBuffer, p.indexStart * 4, src.buffer, src.byteOffset, src.byteLength);
280
+ uploaded += src.byteLength;
281
+ }
282
+ pool.markUploaded();
283
+ return uploaded;
284
+ }
285
+
286
+ uploadInstances(data, count) {
287
+ const bytes = Math.max(64, count * 64);
288
+ if (!this.instanceBuffer || this.instanceBuffer.size < bytes) {
289
+ if (this.instanceBuffer) this.instanceBuffer.destroy();
290
+ this.instanceBuffer = this.device.createBuffer({ size: pow2(bytes, 64 * 256), usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
291
+ }
292
+ if (count) this.device.queue.writeBuffer(this.instanceBuffer, 0, data.buffer, data.byteOffset, count * 64);
293
+ return count * 64;
294
+ }
295
+
296
+ readyTexture(entry, srgb) {
297
+ if (entry && entry.status === 'ready' && !entry.gpu) entry.gpu = this.createTexture(entry.pixels, srgb);
298
+ return entry && entry.gpu ? entry.gpu : null;
299
+ }
300
+
301
+ materialEntries(buffer, map, normal, mr, occlusion, emissive) {
302
+ return [
303
+ { binding: 0, resource: { buffer } },
304
+ { binding: 1, resource: this.sampler },
305
+ { binding: 2, resource: map.view },
306
+ { binding: 3, resource: normal.view },
307
+ { binding: 4, resource: mr.view },
308
+ { binding: 5, resource: occlusion.view },
309
+ { binding: 6, resource: emissive.view },
310
+ ];
311
+ }
312
+
313
+ materialBinding(material, textures, doubleSided) {
314
+ const id = doubleSided ? 'ds' : 'ss';
315
+ let rec = this.materialBindings.get(material);
316
+ if (!rec) {
317
+ rec = {};
318
+ this.materialBindings.set(material, rec);
319
+ }
320
+ const mapGpu = this.readyTexture(material.map ? textures.get(material.map, 'color') : null, true);
321
+ const nrmGpu = this.readyTexture(material.normalMap ? textures.get(material.normalMap, 'normal') : null, false);
322
+ const mrGpu = this.readyTexture(material.metallicRoughnessMap ? textures.get(material.metallicRoughnessMap, 'linear') : null, false);
323
+ const occGpu = this.readyTexture(material.occlusionMap ? textures.get(material.occlusionMap, 'linear') : null, false);
324
+ const emGpu = this.readyTexture(material.emissiveMap ? textures.get(material.emissiveMap, 'color') : null, true);
325
+ const hasMap = !!mapGpu;
326
+ const hasNormalMap = !!nrmGpu;
327
+ const hasMrMap = !!mrGpu;
328
+ const hasOcclusionMap = !!occGpu;
329
+ const hasEmissiveMap = !!emGpu;
330
+ const key = `${hasMap}|${hasNormalMap}|${hasMrMap}|${hasOcclusionMap}|${hasEmissiveMap}`;
331
+ let b = rec[id];
332
+ if (!b || b.key !== key) {
333
+ if (b) b.buffer.destroy();
334
+ packMaterial(this.matData, material, { hasMap, hasNormalMap, hasMrMap, hasOcclusionMap, hasEmissiveMap, doubleSided: doubleSided || material.doubleSided });
335
+ const buffer = this.device.createBuffer({ size: MATERIAL_FLOATS * 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
336
+ this.device.queue.writeBuffer(buffer, 0, this.matData);
337
+ const bindGroup = this.device.createBindGroup({
338
+ layout: this.materialLayout,
339
+ entries: this.materialEntries(buffer, mapGpu || this.whiteTex, nrmGpu || this.flatNormalTex, mrGpu || this.whiteTex, occGpu || this.whiteTex, emGpu || this.whiteTex),
340
+ });
341
+ b = rec[id] = { key, buffer, bindGroup, flags: this.matData[10] };
342
+ }
343
+ return b;
344
+ }
345
+
346
+ overlayBinding(name, rgba) {
347
+ let b = this.overlayBindings.get(name);
348
+ if (b) return b;
349
+ packOverlay(this.matData, rgba);
350
+ const buffer = this.device.createBuffer({ size: MATERIAL_FLOATS * 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
351
+ this.device.queue.writeBuffer(buffer, 0, this.matData);
352
+ b = this.device.createBindGroup({
353
+ layout: this.materialLayout,
354
+ entries: this.materialEntries(buffer, this.whiteTex, this.flatNormalTex, this.whiteTex, this.whiteTex, this.whiteTex),
355
+ });
356
+ this.overlayBindings.set(name, b);
357
+ return b;
358
+ }
359
+
360
+ releaseMaterials(keep) {
361
+ for (const [m, rec] of this.materialBindings) {
362
+ if (keep.has(m)) continue;
363
+ for (const b of Object.values(rec)) b.buffer.destroy();
364
+ this.materialBindings.delete(m);
365
+ }
366
+ }
367
+
368
+ /** What this backend renders with (Renderer.caps). */
369
+ get caps() {
370
+ return {
371
+ msaaSamples: SAMPLE_COUNT,
372
+ anisotropy: 8,
373
+ maxTextureSize: this.device ? this.device.limits.maxTextureDimension2D : 0,
374
+ colorSpace: 'srgb',
375
+ };
376
+ }
377
+
378
+ resize(width, height) {
379
+ if (this.canvas.width !== width || this.canvas.height !== height) {
380
+ this.canvas.width = width;
381
+ this.canvas.height = height;
382
+ }
383
+ }
384
+
385
+ render(draw, frameData, ctx) {
386
+ if (this.lost) return;
387
+ const d = this.device;
388
+ this.ensureTargets();
389
+ d.queue.writeBuffer(this.frameBuffer, 0, frameData.buffer, frameData.byteOffset, frameData.byteLength);
390
+ this.uploadInstances(draw.instanceData, draw.instanceCount);
391
+ const encoder = d.createCommandEncoder();
392
+ const pass = encoder.beginRenderPass({
393
+ colorAttachments: [
394
+ {
395
+ view: this.msaaView,
396
+ resolveTarget: this.present === 'readback' ? this.offscreenView : this.context.getCurrentTexture().createView(),
397
+ clearValue: { r: ctx.background[0], g: ctx.background[1], b: ctx.background[2], a: 1 },
398
+ loadOp: 'clear',
399
+ storeOp: 'discard',
400
+ },
401
+ ],
402
+ depthStencilAttachment: { view: this.depthView, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'discard' },
403
+ });
404
+ pass.setBindGroup(0, this.frameBindGroup);
405
+ if (this.vertexBuffer) {
406
+ pass.setVertexBuffer(0, this.vertexBuffer);
407
+ pass.setIndexBuffer(this.indexBuffer, 'uint32');
408
+ }
409
+ pass.setVertexBuffer(1, this.instanceBuffer);
410
+ let currentPipeline = null;
411
+ const setPipe = (p) => {
412
+ if (p !== currentPipeline) {
413
+ pass.setPipeline(p);
414
+ currentPipeline = p;
415
+ }
416
+ };
417
+ if (this.vertexBuffer) {
418
+ let boundGroup = null;
419
+ const lights = lightTypes(frameData);
420
+ for (const b of draw.batches) {
421
+ const lines = b.kind === 'lines';
422
+ const binding = this.materialBinding(b.material, ctx.textures, b.doubleSided && !b.material.doubleSided);
423
+ const pipe = lines
424
+ ? this.pipeline('lines', { blend: b.transparent, depthWrite: !b.transparent })
425
+ : this.pipeline('mesh', {
426
+ cull: b.doubleSided ? 'none' : 'back',
427
+ frontFace: b.mirrored ? 'cw' : 'ccw',
428
+ blend: b.transparent,
429
+ depthWrite: !b.transparent,
430
+ flags: binding.flags,
431
+ lights,
432
+ });
433
+ setPipe(pipe);
434
+ const group = binding.bindGroup;
435
+ if (group !== boundGroup) {
436
+ pass.setBindGroup(1, group);
437
+ boundGroup = group;
438
+ }
439
+ pass.drawIndexed(b.range.indexCount, b.count, b.range.firstIndex, 0, b.firstInstance);
440
+ }
441
+ const ov = draw.overlays;
442
+ const drawLines = (kind, name, color, list, depthCompare = 'less-equal') => {
443
+ if (!list.length) return;
444
+ setPipe(this.pipeline(kind, { blend: true, depthWrite: false, depthCompare }));
445
+ pass.setBindGroup(1, this.overlayBinding(name, color));
446
+ for (const o of list) pass.drawIndexed(o.range.indexCount, o.count, o.range.firstIndex, 0, o.firstInstance);
447
+ };
448
+ drawLines('lines', 'wireframe', ctx.overlayColors.wireframe, ov.wireframe);
449
+ drawLines('normals', 'normals', ctx.overlayColors.normals, ov.normals);
450
+ if (ov.bbox && ov.bbox.count) drawLines('lines', 'bbox', ctx.overlayColors.bbox, [{ ...ov.bbox, range: ctx.cubeRange }]);
451
+ if (ov.selection && ov.selection.count) drawLines('lines', 'selection', ctx.overlayColors.selection, [{ ...ov.selection, range: ctx.cubeRange }], 'always');
452
+ }
453
+ pass.end();
454
+ const copied = this.present === 'readback' && this.readback(encoder);
455
+ d.queue.submit([encoder.finish()]);
456
+ if (copied) this.startReadback();
457
+ this.lastFrameCopied = copied;
458
+ }
459
+
460
+ async finish() {
461
+ await this.device.queue.onSubmittedWorkDone();
462
+ if (this.readPending) await this.readPending;
463
+ if (this.present === 'readback' && !this.lastFrameCopied && this.offscreen) {
464
+ // the latest frame was rendered while an older readback was in flight
465
+ const encoder = this.device.createCommandEncoder();
466
+ this.readback(encoder);
467
+ this.device.queue.submit([encoder.finish()]);
468
+ this.startReadback();
469
+ await this.readPending;
470
+ this.lastFrameCopied = true;
471
+ }
472
+ }
473
+
474
+ dispose() {
475
+ if (!this.device) return;
476
+ for (const b of [this.vertexBuffer, this.indexBuffer, this.instanceBuffer, this.frameBuffer]) if (b) b.destroy();
477
+ for (const rec of this.materialBindings.values()) for (const b of Object.values(rec)) b.buffer.destroy();
478
+ if (this.msaa) this.msaa.destroy();
479
+ if (this.depth) this.depth.destroy();
480
+ this.device.destroy();
481
+ }
482
+ }