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