@vcollab/shader-webgl2 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,707 @@
1
+ 'use strict';
2
+
3
+ var shaderLibrary = require('@vcollab/shader-library');
4
+
5
+ // src/errors.ts
6
+ var GLPipelineError = class extends Error {
7
+ name = "GLPipelineError";
8
+ };
9
+
10
+ // src/geometry.ts
11
+ var listeners = /* @__PURE__ */ new WeakMap();
12
+ function onDispose(geometry, release) {
13
+ let set = listeners.get(geometry);
14
+ if (set === void 0) {
15
+ set = /* @__PURE__ */ new Set();
16
+ listeners.set(geometry, set);
17
+ }
18
+ set.add(release);
19
+ return () => set.delete(release);
20
+ }
21
+ var GLGeometry = class {
22
+ #gl;
23
+ #attributes = /* @__PURE__ */ new Map();
24
+ /** The buffers this geometry uploaded, and so deletes. */
25
+ #owned = [];
26
+ #indexBuffer;
27
+ #disposed = false;
28
+ #stopSharing = null;
29
+ /** Vertices per attribute: every attribute, its own or shared, holds this many. */
30
+ vertexCount;
31
+ /** How many indices a draw reads. */
32
+ indexCount;
33
+ /**
34
+ * Upload the attributes, and the indices unless shared.
35
+ *
36
+ * @param shares a geometry whose buffers this one reads for every semantic
37
+ * it does not supply itself, and whose indices it draws with. It must
38
+ * outlive this one; disposing it disposes this.
39
+ * @throws {GLPipelineError} if an attribute's `components` is not a positive
40
+ * integer, its data is not a whole number of vertices, two attributes
41
+ * disagree on the vertex count, there are no indices to draw with, the
42
+ * shared geometry is disposed, or a buffer cannot be created. Nothing is
43
+ * left allocated.
44
+ */
45
+ constructor(gl, source, shares) {
46
+ this.#gl = gl;
47
+ if (shares?.disposed) {
48
+ throw new GLPipelineError("cannot share the buffers of a disposed geometry");
49
+ }
50
+ let vertexCount = shares?.vertexCount;
51
+ for (const [semantic, attribute] of source.attributes) {
52
+ const { data, components } = attribute;
53
+ if (!(data instanceof Float32Array || data instanceof Int32Array)) {
54
+ throw new GLPipelineError(`${semantic}: data must be a Float32Array or an Int32Array`);
55
+ }
56
+ if (!Number.isInteger(components) || components < 1) {
57
+ throw new GLPipelineError(
58
+ `${semantic}: components is ${String(components)}, not a positive integer`
59
+ );
60
+ }
61
+ if (data.length % components !== 0) {
62
+ throw new GLPipelineError(
63
+ `${semantic}: ${data.length} values is not a whole number of ${components}-value vertices`
64
+ );
65
+ }
66
+ const count = data.length / components;
67
+ if (vertexCount !== void 0 && count !== vertexCount) {
68
+ throw new GLPipelineError(
69
+ `${semantic} holds ${count} vertices; the geometry has ${vertexCount}`
70
+ );
71
+ }
72
+ vertexCount = count;
73
+ }
74
+ const indices = source.indices;
75
+ if (indices === void 0 && shares === void 0) {
76
+ throw new GLPipelineError("a geometry needs indices, or another geometry to share");
77
+ }
78
+ this.vertexCount = vertexCount ?? 0;
79
+ this.indexCount = indices?.length ?? shares.indexCount;
80
+ const owned = [];
81
+ const savedVertexArray = gl.getParameter(
82
+ gl.VERTEX_ARRAY_BINDING
83
+ );
84
+ const savedArrayBuffer = gl.getParameter(gl.ARRAY_BUFFER_BINDING);
85
+ try {
86
+ for (const [semantic, attribute] of source.attributes) {
87
+ const buffer = gl.createBuffer();
88
+ if (buffer === null)
89
+ throw new GLPipelineError(`could not create a buffer for ${semantic}`);
90
+ owned.push(buffer);
91
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
92
+ gl.bufferData(gl.ARRAY_BUFFER, attribute.data, gl.STATIC_DRAW);
93
+ this.#attributes.set(semantic, {
94
+ buffer,
95
+ components: attribute.components,
96
+ integer: attribute.integer,
97
+ type: attribute.data instanceof Int32Array ? "int" : "float"
98
+ });
99
+ }
100
+ if (indices !== void 0) {
101
+ const buffer = gl.createBuffer();
102
+ if (buffer === null) throw new GLPipelineError("could not create an index buffer");
103
+ owned.push(buffer);
104
+ gl.bindVertexArray(null);
105
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
106
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
107
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
108
+ this.#indexBuffer = buffer;
109
+ } else {
110
+ this.#indexBuffer = null;
111
+ }
112
+ } catch (error) {
113
+ for (const buffer of owned) gl.deleteBuffer(buffer);
114
+ throw error;
115
+ } finally {
116
+ gl.bindBuffer(gl.ARRAY_BUFFER, savedArrayBuffer);
117
+ gl.bindVertexArray(savedVertexArray);
118
+ }
119
+ this.#owned = owned;
120
+ if (shares !== void 0) {
121
+ for (const semantic of shares.semantics) {
122
+ if (!this.#attributes.has(semantic)) {
123
+ this.#attributes.set(semantic, shares.attribute(semantic));
124
+ }
125
+ }
126
+ if (this.#indexBuffer === null) this.#indexBuffer = shares.indexBuffer;
127
+ this.#stopSharing = onDispose(shares, () => this.dispose());
128
+ }
129
+ }
130
+ /** Every semantic this geometry can feed, its own and shared. */
131
+ get semantics() {
132
+ return [...this.#attributes.keys()];
133
+ }
134
+ /** One semantic's buffer and layout, or undefined where it has none. */
135
+ attribute(semantic) {
136
+ return this.#attributes.get(semantic);
137
+ }
138
+ /** The index buffer a draw reads, its own or shared. */
139
+ get indexBuffer() {
140
+ return this.#indexBuffer;
141
+ }
142
+ /** Whether {@link dispose} has been called, here or on a geometry this shares. */
143
+ get disposed() {
144
+ return this.#disposed;
145
+ }
146
+ /**
147
+ * Delete the buffers this geometry uploaded, and tell every pipeline that
148
+ * drew it, so each drops the vertex array it built here. Geometries sharing
149
+ * this one are disposed too. Calling it again does nothing.
150
+ */
151
+ dispose() {
152
+ if (this.#disposed) return;
153
+ this.#disposed = true;
154
+ this.#stopSharing?.();
155
+ this.#stopSharing = null;
156
+ const waiting = listeners.get(this);
157
+ listeners.delete(this);
158
+ for (const release of waiting ?? []) release();
159
+ for (const buffer of this.#owned) this.#gl.deleteBuffer(buffer);
160
+ this.#owned = [];
161
+ this.#attributes.clear();
162
+ }
163
+ };
164
+ var EMPTY_COLOR = new Uint32Array([shaderLibrary.PICK_EMPTY, shaderLibrary.PICK_EMPTY, shaderLibrary.PICK_EMPTY, shaderLibrary.PICK_EMPTY]);
165
+ var FAR_DEPTH = new Float32Array([1]);
166
+ var PickPass = class {
167
+ #gl;
168
+ #framebuffer;
169
+ #target = null;
170
+ #depth = null;
171
+ #width = 0;
172
+ #height = 0;
173
+ #readback = new Uint32Array(4);
174
+ constructor(gl) {
175
+ this.#gl = gl;
176
+ const framebuffer = gl.createFramebuffer();
177
+ if (framebuffer === null) throw new GLPipelineError("could not create a pick framebuffer");
178
+ this.#framebuffer = framebuffer;
179
+ }
180
+ /**
181
+ * Match the target to the viewport.
182
+ *
183
+ * `rgba32ui` for the attachment, with a depth buffer beside it so the
184
+ * nearest primitive wins exactly as it does on screen. Neither is
185
+ * multisampled: an integer attachment cannot be. Sizes are floored, and a
186
+ * call at the current floored size does nothing. The caller's texture,
187
+ * renderbuffer and framebuffer bindings are put back afterwards.
188
+ *
189
+ * @throws {GLPipelineError} if the texture or renderbuffer cannot be created
190
+ * or the framebuffer is not complete; the pass is then left with no target.
191
+ */
192
+ resize(width, height) {
193
+ const gl = this.#gl;
194
+ const w = Math.max(1, Math.floor(width));
195
+ const h = Math.max(1, Math.floor(height));
196
+ if (this.#target !== null && w === this.#width && h === this.#height) return;
197
+ this.#release();
198
+ const savedTexture = gl.getParameter(gl.TEXTURE_BINDING_2D);
199
+ const savedRenderbuffer = gl.getParameter(gl.RENDERBUFFER_BINDING);
200
+ const savedDraw = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);
201
+ const savedRead = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);
202
+ let target = null;
203
+ let depth = null;
204
+ try {
205
+ target = gl.createTexture();
206
+ if (target === null) throw new GLPipelineError("could not create a pick target texture");
207
+ gl.bindTexture(gl.TEXTURE_2D, target);
208
+ gl.texImage2D(
209
+ gl.TEXTURE_2D,
210
+ 0,
211
+ gl.RGBA32UI,
212
+ w,
213
+ h,
214
+ 0,
215
+ gl.RGBA_INTEGER,
216
+ gl.UNSIGNED_INT,
217
+ null
218
+ );
219
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
220
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
221
+ depth = gl.createRenderbuffer();
222
+ if (depth === null) throw new GLPipelineError("could not create a pick depth buffer");
223
+ gl.bindRenderbuffer(gl.RENDERBUFFER, depth);
224
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT24, w, h);
225
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.#framebuffer);
226
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, target, 0);
227
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depth);
228
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
229
+ if (status !== gl.FRAMEBUFFER_COMPLETE) {
230
+ throw new GLPipelineError(
231
+ `the pick framebuffer is not complete: 0x${status.toString(16)}`
232
+ );
233
+ }
234
+ this.#target = target;
235
+ this.#depth = depth;
236
+ this.#width = w;
237
+ this.#height = h;
238
+ target = null;
239
+ depth = null;
240
+ } finally {
241
+ if (target !== null) gl.deleteTexture(target);
242
+ if (depth !== null) gl.deleteRenderbuffer(depth);
243
+ gl.bindTexture(gl.TEXTURE_2D, savedTexture);
244
+ gl.bindRenderbuffer(gl.RENDERBUFFER, savedRenderbuffer);
245
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, savedDraw);
246
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, savedRead);
247
+ }
248
+ }
249
+ /**
250
+ * Draw the scene's pick pass and read one pixel.
251
+ *
252
+ * The target is cleared, then `drawScene` is called once with a {@link PickDraw}
253
+ * and issues every draw the pick should see: for each occurrence, set its
254
+ * pick pipeline's uniforms and textures as the color pass had them, then
255
+ * `draw(pipeline, geometry)`. Nearest wins, as on screen.
256
+ *
257
+ * Only the pixel asked for is drawn: after the clear the scissor is set to
258
+ * that one pixel, so a scene of thousands of draws shades one fragment each.
259
+ * The pass sets the state it depends on — every color channel and depth
260
+ * writable, `LESS` depth testing, no blending — and afterwards puts back
261
+ * each of those, the scissor test and box, the viewport and the caller's
262
+ * framebuffers, even if a draw throws. Face culling is left as the caller set
263
+ * it, so the pick honors winding exactly as the color pass does. The draws
264
+ * also change the current program and texture bindings (see
265
+ * {@link GLPipeline.draw}).
266
+ *
267
+ * @param x horizontal position in framebuffer pixels, from the left.
268
+ * @param y vertical position in framebuffer pixels, from the **bottom** —
269
+ * GL's origin, not the DOM's. {@link fromCanvasPoint} converts.
270
+ * @param drawScene issues the draws, through the `draw` it is given.
271
+ * @returns the hit, or `null` where nothing was drawn or the point is
272
+ * outside — in which case `drawScene` is not called.
273
+ * @throws {GLPipelineError} before {@link resize} has been called, if a draw
274
+ * names a pipeline that is not a pick pipeline (one writing a color into
275
+ * this integer target would read back as garbage), or if a pipeline
276
+ * refuses to draw. Anything `drawScene` throws is rethrown.
277
+ */
278
+ pick(x, y, drawScene) {
279
+ const gl = this.#gl;
280
+ if (this.#target === null)
281
+ throw new GLPipelineError("the pick pass has no target; call resize first");
282
+ const px = Math.floor(x);
283
+ const py = Math.floor(y);
284
+ if (px < 0 || py < 0 || px >= this.#width || py >= this.#height) return null;
285
+ const saved = {
286
+ draw: gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING),
287
+ read: gl.getParameter(gl.READ_FRAMEBUFFER_BINDING),
288
+ viewport: gl.getParameter(gl.VIEWPORT),
289
+ blend: gl.isEnabled(gl.BLEND),
290
+ depthTest: gl.isEnabled(gl.DEPTH_TEST),
291
+ scissorTest: gl.isEnabled(gl.SCISSOR_TEST),
292
+ scissorBox: gl.getParameter(gl.SCISSOR_BOX),
293
+ depthMask: gl.getParameter(gl.DEPTH_WRITEMASK),
294
+ colorMask: gl.getParameter(gl.COLOR_WRITEMASK),
295
+ depthFunc: gl.getParameter(gl.DEPTH_FUNC)
296
+ };
297
+ this.#readback.fill(shaderLibrary.PICK_EMPTY);
298
+ try {
299
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.#framebuffer);
300
+ gl.viewport(0, 0, this.#width, this.#height);
301
+ gl.disable(gl.SCISSOR_TEST);
302
+ gl.colorMask(true, true, true, true);
303
+ gl.depthMask(true);
304
+ gl.clearBufferuiv(gl.COLOR, 0, EMPTY_COLOR);
305
+ gl.clearBufferfv(gl.DEPTH, 0, FAR_DEPTH);
306
+ gl.enable(gl.DEPTH_TEST);
307
+ gl.depthFunc(gl.LESS);
308
+ gl.disable(gl.BLEND);
309
+ gl.enable(gl.SCISSOR_TEST);
310
+ gl.scissor(px, py, 1, 1);
311
+ drawScene((pipeline, geometry) => {
312
+ if (!pipeline.envelope.pipeline.capabilities.includes(shaderLibrary.PICK_CAPABILITY)) {
313
+ throw new GLPipelineError(
314
+ `${pipeline.envelope.pipeline.id} is not a pick pipeline; the pick target holds identifiers, and a color written into it reads back as garbage`
315
+ );
316
+ }
317
+ pipeline.draw(geometry);
318
+ });
319
+ gl.readPixels(px, py, 1, 1, gl.RGBA_INTEGER, gl.UNSIGNED_INT, this.#readback);
320
+ } finally {
321
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, saved.draw);
322
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, saved.read);
323
+ const [vx, vy, vw, vh] = saved.viewport;
324
+ gl.viewport(vx, vy, vw, vh);
325
+ const toggle = (cap, on) => on ? gl.enable(cap) : gl.disable(cap);
326
+ toggle(gl.BLEND, saved.blend);
327
+ toggle(gl.DEPTH_TEST, saved.depthTest);
328
+ toggle(gl.SCISSOR_TEST, saved.scissorTest);
329
+ const [sx, sy, sw, sh] = saved.scissorBox;
330
+ gl.scissor(sx, sy, sw, sh);
331
+ gl.depthMask(saved.depthMask);
332
+ const [r, g, b, a] = saved.colorMask;
333
+ gl.colorMask(r, g, b, a);
334
+ gl.depthFunc(saved.depthFunc);
335
+ }
336
+ const hit = shaderLibrary.decodePick(this.#readback);
337
+ return hit === null ? null : { ...hit, x: px, y: py };
338
+ }
339
+ /**
340
+ * A canvas point as {@link pick} wants it: the integer device pixel under
341
+ * the point, counted from the bottom-left.
342
+ *
343
+ * A DOM event gives CSS pixels from the top-left of the element; GL reads
344
+ * device pixels from the bottom-left. Getting this wrong picks a mirrored
345
+ * point, which looks plausible near the middle and wrong everywhere else.
346
+ * The top CSS row maps to row `height - 1`; a point on or past an edge maps
347
+ * outside the target, where {@link pick} returns `null`.
348
+ */
349
+ static fromCanvasPoint(canvas, offsetX, offsetY) {
350
+ const scaleX = canvas.width / Math.max(1, canvas.clientWidth);
351
+ const scaleY = canvas.height / Math.max(1, canvas.clientHeight);
352
+ return {
353
+ x: Math.floor(offsetX * scaleX),
354
+ y: canvas.height - 1 - Math.floor(offsetY * scaleY)
355
+ };
356
+ }
357
+ /** Release the target, its depth buffer and the framebuffer. */
358
+ dispose() {
359
+ this.#gl.deleteFramebuffer(this.#framebuffer);
360
+ this.#release();
361
+ }
362
+ #release() {
363
+ const gl = this.#gl;
364
+ if (this.#target !== null) gl.deleteTexture(this.#target);
365
+ if (this.#depth !== null) gl.deleteRenderbuffer(this.#depth);
366
+ this.#target = null;
367
+ this.#depth = null;
368
+ this.#width = 0;
369
+ this.#height = 0;
370
+ }
371
+ };
372
+ var UNIFORM_BLOCK_NAME = "GlobalParams_std140";
373
+ var UNIFORM_BLOCK_BINDING = 0;
374
+ function attributeShape(input) {
375
+ const match = /^(i?)vec([234])$/.exec(input.type);
376
+ if (match !== null) return { integer: match[1] === "i", width: Number(match[2]) };
377
+ if (input.type === "float") return { integer: false, width: 1 };
378
+ if (input.type === "int") return { integer: true, width: 1 };
379
+ throw new GLPipelineError(
380
+ `${input.name} is declared ${input.type}; only float, vecN, int and ivecN attributes are supported`
381
+ );
382
+ }
383
+ function compile(gl, type, source, stage) {
384
+ const shader = gl.createShader(type);
385
+ if (shader === null) throw new GLPipelineError(`could not create a ${stage} shader`);
386
+ gl.shaderSource(shader, source);
387
+ gl.compileShader(shader);
388
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
389
+ const log = gl.getShaderInfoLog(shader);
390
+ gl.deleteShader(shader);
391
+ throw new GLPipelineError(`the ${stage} stage did not compile on this driver:
392
+ ${log}`);
393
+ }
394
+ return shader;
395
+ }
396
+ function linkProgram(gl, vertex, fragment) {
397
+ const vertexShader = compile(gl, gl.VERTEX_SHADER, vertex, "vertex");
398
+ let fragmentShader;
399
+ try {
400
+ fragmentShader = compile(gl, gl.FRAGMENT_SHADER, fragment, "fragment");
401
+ } catch (error) {
402
+ gl.deleteShader(vertexShader);
403
+ throw error;
404
+ }
405
+ const program = gl.createProgram();
406
+ if (program === null) {
407
+ gl.deleteShader(vertexShader);
408
+ gl.deleteShader(fragmentShader);
409
+ throw new GLPipelineError("could not create a program");
410
+ }
411
+ gl.attachShader(program, vertexShader);
412
+ gl.attachShader(program, fragmentShader);
413
+ gl.linkProgram(program);
414
+ gl.deleteShader(vertexShader);
415
+ gl.deleteShader(fragmentShader);
416
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
417
+ const log = gl.getProgramInfoLog(program);
418
+ gl.deleteProgram(program);
419
+ throw new GLPipelineError(`the stage pair did not link on this driver:
420
+ ${log}`);
421
+ }
422
+ const blockIndex = gl.getUniformBlockIndex(program, UNIFORM_BLOCK_NAME);
423
+ if (blockIndex !== gl.INVALID_INDEX) {
424
+ gl.uniformBlockBinding(program, blockIndex, UNIFORM_BLOCK_BINDING);
425
+ }
426
+ return program;
427
+ }
428
+ var GLPipeline = class {
429
+ #gl;
430
+ #program;
431
+ #ubo;
432
+ /** The vertex array built over each geometry this has drawn. */
433
+ #bindings = /* @__PURE__ */ new Map();
434
+ /** Each contract input's shape and its location in this program, read once. */
435
+ #inputs;
436
+ #textures = /* @__PURE__ */ new Map();
437
+ /** Each binding's sampler uniform location, in `bindings.all` order. */
438
+ #samplerLocations;
439
+ /** A byte view of `uniforms.buffer`, made once. */
440
+ #uniformBytes;
441
+ #disposed = false;
442
+ /** The envelope this was built from. */
443
+ envelope;
444
+ /** Its language block: layout, bindings and sources. */
445
+ block;
446
+ /** Its sampler bindings, by semantic. */
447
+ bindings;
448
+ /**
449
+ * The uniform block to write into. The caller sets whatever the pipeline
450
+ * declares before each draw that needs different values; {@link draw}
451
+ * uploads it.
452
+ */
453
+ uniforms;
454
+ /**
455
+ * @throws {GLPipelineError} if the envelope lacks a stage, declares an
456
+ * attribute type this cannot feed, the driver rejects the text, a GL
457
+ * object cannot be created, or the driver sizes the uniform block too
458
+ * small for the layout the build reflected. Anything created before the
459
+ * failure is freed.
460
+ */
461
+ constructor(gl, envelope, language = "glsl") {
462
+ this.#gl = gl;
463
+ this.envelope = envelope;
464
+ this.block = shaderLibrary.ShaderSet.language(envelope, language);
465
+ const stages = this.block.stages;
466
+ if (stages.vertex === void 0 || stages.fragment === void 0) {
467
+ throw new GLPipelineError(`${envelope.pipeline.id} does not carry both stages`);
468
+ }
469
+ const shapes = envelope.pipeline.inputs.map((input) => ({
470
+ input,
471
+ shape: attributeShape(input)
472
+ }));
473
+ const program = linkProgram(gl, stages.vertex.source, stages.fragment.source);
474
+ try {
475
+ this.bindings = new shaderLibrary.ResourceBindings(this.block);
476
+ this.uniforms = new shaderLibrary.UniformBlock(this.block);
477
+ this.#uniformBytes = new Uint8Array(this.uniforms.buffer);
478
+ let bufferSize = this.block.blockSize;
479
+ const blockIndex = gl.getUniformBlockIndex(program, UNIFORM_BLOCK_NAME);
480
+ if (blockIndex !== gl.INVALID_INDEX) {
481
+ const size = gl.getActiveUniformBlockParameter(
482
+ program,
483
+ blockIndex,
484
+ gl.UNIFORM_BLOCK_DATA_SIZE
485
+ );
486
+ const end = Math.max(
487
+ 0,
488
+ ...Object.values(this.block.layout).map((member) => member.offset + member.size)
489
+ );
490
+ if (typeof size !== "number" || size < end) {
491
+ throw new GLPipelineError(
492
+ `${envelope.pipeline.id}: the driver sizes ${UNIFORM_BLOCK_NAME} at ${String(size)} bytes, too small for the layout the build reflected, which ends at byte ${end}`
493
+ );
494
+ }
495
+ bufferSize = Math.max(bufferSize, size);
496
+ }
497
+ this.#samplerLocations = this.bindings.all.map(
498
+ (record) => gl.getUniformLocation(program, record.uniform)
499
+ );
500
+ this.#inputs = shapes.map(({ input, shape }) => ({
501
+ input,
502
+ shape,
503
+ location: gl.getAttribLocation(program, input.name)
504
+ }));
505
+ const ubo = gl.createBuffer();
506
+ if (ubo === null) throw new GLPipelineError("could not create a uniform buffer");
507
+ gl.bindBuffer(gl.UNIFORM_BUFFER, ubo);
508
+ gl.bufferData(gl.UNIFORM_BUFFER, bufferSize, gl.DYNAMIC_DRAW);
509
+ this.#program = program;
510
+ this.#ubo = ubo;
511
+ } catch (error) {
512
+ gl.deleteProgram(program);
513
+ throw error;
514
+ }
515
+ }
516
+ /** The linked program, for a caller that needs it directly. */
517
+ get program() {
518
+ return this.#program;
519
+ }
520
+ /**
521
+ * Give a semantic its texture.
522
+ *
523
+ * By semantic, because the name a table or texture is declared under never
524
+ * reaches the linked program: GLSL ES 3.00 has no binding qualifier for
525
+ * samplers, so the cross-compiler pairs each texture with a sampler and names
526
+ * the combination itself. The envelope's record is the only route across.
527
+ *
528
+ * The texture is used by every draw until it is replaced, so a caller giving
529
+ * each occurrence a table of its own sets it before that occurrence's draw.
530
+ * An integer table (`usampler2D`) must use `NEAREST` filtering and no
531
+ * mipmaps, or the texture is incomplete and every fetch returns zero.
532
+ */
533
+ setTexture(semantic, texture) {
534
+ if (texture === null) this.#textures.delete(semantic);
535
+ else this.#textures.set(semantic, texture);
536
+ }
537
+ /** Every semantic this pipeline expects a texture for. */
538
+ get requiredSemantics() {
539
+ return this.bindings.semantics;
540
+ }
541
+ /**
542
+ * Check a geometry against this pipeline's contract and build the vertex
543
+ * array that reads it, without drawing.
544
+ *
545
+ * {@link draw} does this on first use; calling it ahead moves a refusal to
546
+ * where the geometry is made rather than the first frame. An attribute the
547
+ * geometry does not supply is left as a **disabled array with a constant**,
548
+ * which is what a viewer does for data a draw does not have — the same "off
549
+ * state is data" the always-present features rely on. The contract's
550
+ * declared width wins over the source's, so a `vec3` read from a wider field
551
+ * takes the first three values of each vertex.
552
+ *
553
+ * @throws {GLPipelineError} if the geometry or this pipeline is disposed, a
554
+ * source's element type or `integer` flag does not match the declared
555
+ * type, its `components` is narrower than the declared width, or the
556
+ * vertex array cannot be created. Nothing is kept for the geometry then.
557
+ */
558
+ prepare(geometry) {
559
+ this.#binding(geometry);
560
+ }
561
+ /**
562
+ * Forget the vertex array built over one geometry, as when it will not be
563
+ * drawn by this pipeline again. Disposing the geometry does this for every
564
+ * pipeline that drew it.
565
+ */
566
+ release(geometry) {
567
+ const binding = this.#bindings.get(geometry);
568
+ if (binding === void 0) return;
569
+ this.#bindings.delete(geometry);
570
+ binding.forget();
571
+ this.#gl.deleteVertexArray(binding.vao);
572
+ }
573
+ /**
574
+ * Draw a geometry, after uploading the uniform block and binding every
575
+ * resource.
576
+ *
577
+ * The uniforms and textures are whatever was last set, so drawing one
578
+ * geometry at several places — the occurrences of one mesh — is a loop of
579
+ * "set this occurrence's values, draw". A geometry with no indices draws
580
+ * nothing. Leaves the current program, the active texture unit, the texture
581
+ * bound on each of the pipeline's units and the array buffer binding
582
+ * changed, and no vertex array bound.
583
+ *
584
+ * @throws {GLPipelineError} if any semantic in {@link requiredSemantics} has
585
+ * no texture (the message names every one missing), or for anything
586
+ * {@link prepare} refuses.
587
+ */
588
+ draw(geometry) {
589
+ const gl = this.#gl;
590
+ if (this.#disposed) throw new GLPipelineError(`${this.envelope.pipeline.id} is disposed`);
591
+ const missing = this.requiredSemantics.filter((semantic) => !this.#textures.has(semantic));
592
+ if (missing.length > 0) {
593
+ throw new GLPipelineError(
594
+ `${this.envelope.pipeline.id} has no texture for: ${missing.join(", ")}`
595
+ );
596
+ }
597
+ const binding = this.#binding(geometry);
598
+ if (geometry.indexCount === 0) return;
599
+ gl.useProgram(this.#program);
600
+ gl.bindBuffer(gl.UNIFORM_BUFFER, this.#ubo);
601
+ gl.bufferSubData(gl.UNIFORM_BUFFER, 0, this.#uniformBytes);
602
+ gl.bindBufferBase(gl.UNIFORM_BUFFER, UNIFORM_BLOCK_BINDING, this.#ubo);
603
+ this.bindings.all.forEach((record, index) => {
604
+ gl.activeTexture(gl.TEXTURE0 + record.unit);
605
+ gl.bindTexture(gl.TEXTURE_2D, this.#textures.get(record.semantic));
606
+ const location = this.#samplerLocations[index];
607
+ if (location !== null) gl.uniform1i(location, record.unit);
608
+ });
609
+ for (const { location, integer } of binding.absent) {
610
+ if (integer) gl.vertexAttribI4i(location, 0, 0, 0, 0);
611
+ else gl.vertexAttrib4f(location, 0, 0, 0, 0);
612
+ }
613
+ gl.bindVertexArray(binding.vao);
614
+ gl.drawElements(gl.TRIANGLES, geometry.indexCount, gl.UNSIGNED_INT, 0);
615
+ gl.bindVertexArray(null);
616
+ }
617
+ /** Whether {@link dispose} has been called. */
618
+ get disposed() {
619
+ return this.#disposed;
620
+ }
621
+ /**
622
+ * Release the GL objects this owns: the program, the uniform buffer and
623
+ * every vertex array it built. Geometries and textures given to it are the
624
+ * caller's and are left alone. Calling it again does nothing.
625
+ */
626
+ dispose() {
627
+ if (this.#disposed) return;
628
+ this.#disposed = true;
629
+ for (const geometry of [...this.#bindings.keys()]) this.release(geometry);
630
+ const gl = this.#gl;
631
+ gl.deleteProgram(this.#program);
632
+ gl.deleteBuffer(this.#ubo);
633
+ this.#textures.clear();
634
+ }
635
+ /** The vertex array over a geometry: the one built before, or a new one. */
636
+ #binding(geometry) {
637
+ if (this.#disposed) {
638
+ throw new GLPipelineError(`${this.envelope.pipeline.id} is disposed`);
639
+ }
640
+ if (geometry.disposed) throw new GLPipelineError("the geometry is disposed");
641
+ const known = this.#bindings.get(geometry);
642
+ if (known !== void 0) return known;
643
+ const gl = this.#gl;
644
+ const plan = this.#inputs.map(({ input, shape, location }) => {
645
+ const source = geometry.attribute(input.semantic);
646
+ if (source !== void 0) {
647
+ const label = `${input.semantic} (${input.name}, ${input.type})`;
648
+ if (source.integer !== shape.integer) {
649
+ throw new GLPipelineError(
650
+ `${label} is ${shape.integer ? "an integer" : "a float"} attribute; the source says integer: ${source.integer}`
651
+ );
652
+ }
653
+ if (source.type !== (shape.integer ? "int" : "float")) {
654
+ throw new GLPipelineError(
655
+ `${label} needs ${shape.integer ? "Int32Array" : "Float32Array"} data`
656
+ );
657
+ }
658
+ if (source.components < shape.width) {
659
+ throw new GLPipelineError(
660
+ `${label} reads ${shape.width} values per vertex; the source carries ${source.components}`
661
+ );
662
+ }
663
+ }
664
+ return { shape, source, location };
665
+ });
666
+ const vao = gl.createVertexArray();
667
+ if (vao === null) throw new GLPipelineError("could not create a vertex array");
668
+ const absent = [];
669
+ gl.bindVertexArray(vao);
670
+ for (const { shape, source, location } of plan) {
671
+ if (location < 0) continue;
672
+ if (source === void 0) {
673
+ gl.disableVertexAttribArray(location);
674
+ absent.push({ location, integer: shape.integer });
675
+ continue;
676
+ }
677
+ gl.bindBuffer(gl.ARRAY_BUFFER, source.buffer);
678
+ gl.enableVertexAttribArray(location);
679
+ const stride = source.components * 4;
680
+ if (shape.integer) gl.vertexAttribIPointer(location, shape.width, gl.INT, stride, 0);
681
+ else gl.vertexAttribPointer(location, shape.width, gl.FLOAT, false, stride, 0);
682
+ }
683
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.indexBuffer);
684
+ gl.bindVertexArray(null);
685
+ const binding = {
686
+ vao,
687
+ absent,
688
+ forget: onDispose(geometry, () => this.release(geometry))
689
+ };
690
+ this.#bindings.set(geometry, binding);
691
+ return binding;
692
+ }
693
+ };
694
+
695
+ // src/version.ts
696
+ var VERSION = "2.0.0";
697
+
698
+ exports.GLGeometry = GLGeometry;
699
+ exports.GLPipeline = GLPipeline;
700
+ exports.GLPipelineError = GLPipelineError;
701
+ exports.PickPass = PickPass;
702
+ exports.UNIFORM_BLOCK_BINDING = UNIFORM_BLOCK_BINDING;
703
+ exports.UNIFORM_BLOCK_NAME = UNIFORM_BLOCK_NAME;
704
+ exports.VERSION = VERSION;
705
+ exports.linkProgram = linkProgram;
706
+ //# sourceMappingURL=index.cjs.map
707
+ //# sourceMappingURL=index.cjs.map