@vcollab/shader-library 1.0.0 → 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 CHANGED
@@ -62,6 +62,82 @@ var ResourceBindings = class {
62
62
  }
63
63
  };
64
64
 
65
+ // src/blocks.ts
66
+ var TableBlockError = class extends Error {
67
+ name = "TableBlockError";
68
+ };
69
+ var INT_ROWS = 2 ** 31;
70
+ var TableBlocks = class {
71
+ #bases = [];
72
+ #owners = [];
73
+ #rows = 0;
74
+ /** The most rows the table may hold. */
75
+ maxRows;
76
+ /**
77
+ * @param options.maxRows the most rows the table may hold — the capacity of
78
+ * the texture it will be uploaded to, say. At most, and by default, 2³¹:
79
+ * the shader adds the base to an `int`.
80
+ * @throws {TableBlockError} if `maxRows` is not a positive integer no larger
81
+ * than 2³¹.
82
+ */
83
+ constructor(options = {}) {
84
+ const maxRows = options.maxRows ?? INT_ROWS;
85
+ if (!Number.isInteger(maxRows) || maxRows < 1 || maxRows > INT_ROWS) {
86
+ throw new TableBlockError(
87
+ `maxRows is ${String(maxRows)}; it must be a positive integer no larger than 2^31`
88
+ );
89
+ }
90
+ this.maxRows = maxRows;
91
+ }
92
+ /** Rows given out so far: the size the table must be. */
93
+ get rows() {
94
+ return this.#rows;
95
+ }
96
+ /** How many blocks have been given out. */
97
+ get size() {
98
+ return this.#bases.length;
99
+ }
100
+ /**
101
+ * Give out the next `rows` rows.
102
+ *
103
+ * @returns the block's base: the uniform to draw the owner with, and where
104
+ * its rows start in the table.
105
+ * @throws {TableBlockError} if `rows` is not a positive integer, or the
106
+ * table would grow past {@link maxRows}. Nothing is given out then.
107
+ */
108
+ allocate(rows, owner) {
109
+ if (!Number.isInteger(rows) || rows < 1) {
110
+ throw new TableBlockError(`a block is a positive whole number of rows, not ${String(rows)}`);
111
+ }
112
+ if (this.#rows + rows > this.maxRows) {
113
+ throw new TableBlockError(
114
+ `${rows} rows at ${this.#rows} would take the table past its ${this.maxRows} rows`
115
+ );
116
+ }
117
+ const base = this.#rows;
118
+ this.#bases.push(base);
119
+ this.#owners.push(owner);
120
+ this.#rows += rows;
121
+ return base;
122
+ }
123
+ /**
124
+ * The block a row falls in — a picked `groupId`, say — or `null` when no
125
+ * block holds it.
126
+ */
127
+ locate(row) {
128
+ if (!Number.isInteger(row) || row < 0 || row >= this.#rows) return null;
129
+ let low = 0;
130
+ let high = this.#bases.length - 1;
131
+ while (low < high) {
132
+ const middle = Math.floor((low + high + 1) / 2);
133
+ if (this.#bases[middle] <= row) low = middle;
134
+ else high = middle - 1;
135
+ }
136
+ const base = this.#bases[low];
137
+ return { owner: this.#owners[low], base, offset: row - base };
138
+ }
139
+ };
140
+
65
141
  // src/encoding.ts
66
142
  var ELEMENTS = {
67
143
  float: { kind: "float", width: 1 },
@@ -131,6 +207,25 @@ var SCHEMA_VERSION = 3;
131
207
  var ShaderSetError = class extends Error {
132
208
  name = "ShaderSetError";
133
209
  };
210
+ function pathProblem(path) {
211
+ if (path.length === 0) return "is empty";
212
+ if (/[\u0000-\u001f\u007f-\u009f\\:]/.test(path)) {
213
+ return "holds a backslash, a colon or a control character";
214
+ }
215
+ if (path.startsWith("/")) return "is absolute";
216
+ if (path.split("/").some((part) => part === "" || part === "." || part === "..")) {
217
+ return 'has an empty, "." or ".." segment';
218
+ }
219
+ return void 0;
220
+ }
221
+ function assertPath(path, what) {
222
+ const problem = pathProblem(path);
223
+ if (problem !== void 0) {
224
+ throw new ShaderSetError(
225
+ `${what} ${JSON.stringify(path)} ${problem}; a path inside the set is plain and relative.`
226
+ );
227
+ }
228
+ }
134
229
  function absoluteBase(baseUrl) {
135
230
  if (baseUrl instanceof URL) return new URL(baseUrl.href);
136
231
  if (URL.canParse(baseUrl)) return new URL(baseUrl);
@@ -144,7 +239,11 @@ function fetchSource(baseUrl, init) {
144
239
  const base = absoluteBase(baseUrl);
145
240
  if (!base.pathname.endsWith("/")) base.pathname += "/";
146
241
  const read = async (path) => {
242
+ assertPath(path, "the set path");
147
243
  const url = new URL(path, base);
244
+ if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) {
245
+ throw new ShaderSetError(`${url.href} is outside the set at ${base.href}.`);
246
+ }
148
247
  const response = await fetch(url, init);
149
248
  if (!response.ok) {
150
249
  throw new ShaderSetError(
@@ -164,6 +263,7 @@ function fsSource(directory) {
164
263
  import('fs/promises'),
165
264
  import('path')
166
265
  ]);
266
+ assertPath(path, "the set path");
167
267
  const full = join(directory, ...path.split("/"));
168
268
  try {
169
269
  return JSON.parse(await readFile(full, "utf8"));
@@ -202,6 +302,7 @@ function assertEntry(entry, index) {
202
302
  throw new ShaderSetError(`registry.json entry ${entry.id} has no ${field}.`);
203
303
  }
204
304
  }
305
+ assertPath(entry.envelope, `registry.json entry ${entry.id} has the envelope path`);
205
306
  assertTags(entry.capabilities, `the capabilities of registry.json entry ${entry.id}`);
206
307
  }
207
308
  function asRegistry(document) {
@@ -214,6 +315,15 @@ function asRegistry(document) {
214
315
  }
215
316
  assertTags(document.capabilityVocabulary, "the capabilityVocabulary of registry.json");
216
317
  document.pipelines.forEach(assertEntry);
318
+ const vocabulary = new Set(document.capabilityVocabulary);
319
+ for (const entry of document.pipelines) {
320
+ const unknown = entry.capabilities.filter((tag) => !vocabulary.has(tag));
321
+ if (unknown.length > 0) {
322
+ throw new ShaderSetError(
323
+ `registry.json entry ${entry.id} carries ${unknown.join(", ")}, which capabilityVocabulary does not declare.`
324
+ );
325
+ }
326
+ }
217
327
  const ids = document.pipelines.map((entry) => entry.id);
218
328
  const repeated = ids.filter((id, index) => ids.indexOf(id) !== index);
219
329
  if (repeated.length > 0) {
@@ -253,6 +363,13 @@ function asEnvelope(document, entry) {
253
363
  );
254
364
  }
255
365
  assertTags(envelope.pipeline.capabilities, `the capabilities in the envelope for ${entry.id}`);
366
+ const selected = new Set(entry.capabilities);
367
+ const carried = new Set(envelope.pipeline.capabilities);
368
+ if (selected.size !== carried.size || [...carried].some((tag) => !selected.has(tag))) {
369
+ throw new ShaderSetError(
370
+ `the envelope for ${entry.id} declares the capabilities [${[...carried].sort().join(", ")}], but the index entry that selected it records [${[...selected].sort().join(", ")}].`
371
+ );
372
+ }
256
373
  if (!isObject(envelope.languages)) {
257
374
  throw new ShaderSetError(`the envelope for ${entry.id} carries no languages.`);
258
375
  }
@@ -538,7 +655,7 @@ function capabilitiesInUse(entries) {
538
655
  var PICK_CAPABILITY = "pick";
539
656
  var PICK_EMPTY = 4294967295;
540
657
  var PICK_RESERVED = 0;
541
- var PICK_CHANNELS = ["primitiveId", "depth", "reserved0", "reserved1"];
658
+ var PICK_CHANNELS = ["primitiveId", "depth", "groupId", "reserved"];
542
659
  var DEFORM_CAPABILITIES = ["deform3", "deform6"];
543
660
  var PickDecodeError = class extends Error {
544
661
  name = "PickDecodeError";
@@ -563,7 +680,7 @@ function decodePick(texel, offset = 0) {
563
680
  const primitiveId = texel[offset];
564
681
  if (primitiveId === PICK_EMPTY) return null;
565
682
  asUint[0] = texel[offset + 1];
566
- return { primitiveId, depth: asFloat[0] };
683
+ return { primitiveId, depth: asFloat[0], groupId: texel[offset + 2] };
567
684
  }
568
685
  function pickPipelineFor(registry, color) {
569
686
  const available = /* @__PURE__ */ new Set([...color.capabilities, PICK_CAPABILITY]);
@@ -588,7 +705,7 @@ function pickPipelineFor(registry, color) {
588
705
  }
589
706
 
590
707
  // src/version.ts
591
- var VERSION = "1.0.0";
708
+ var VERSION = "2.0.0";
592
709
 
593
710
  exports.BindingError = BindingError;
594
711
  exports.PICK_CAPABILITY = PICK_CAPABILITY;
@@ -601,6 +718,8 @@ exports.ResourceBindings = ResourceBindings;
601
718
  exports.SCHEMA_VERSION = SCHEMA_VERSION;
602
719
  exports.ShaderSet = ShaderSet;
603
720
  exports.ShaderSetError = ShaderSetError;
721
+ exports.TableBlockError = TableBlockError;
722
+ exports.TableBlocks = TableBlocks;
604
723
  exports.UniformBlock = UniformBlock;
605
724
  exports.UniformPackError = UniformPackError;
606
725
  exports.VERSION = VERSION;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bind.ts","../src/encoding.ts","../src/manifest.ts","../src/load.ts","../src/pack.ts","../src/select.ts","../src/pick.ts","../src/version.ts"],"names":[],"mappings":";;;AAqBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EACpB,IAAA,GAAO,cAAA;AAC3B;AASO,IAAM,mBAAN,MAAuB;AAAA,EACnB,WAAA;AAAA;AAAA,EAGA,GAAA;AAAA,EAET,YAAY,KAAA,EAAsB;AAChC,IAAA,IAAA,CAAK,GAAA,GAAM,KAAA,CAAM,QAAA,IAAY,EAAC;AAC9B,IAAA,MAAM,UAAA,uBAAiB,GAAA,EAA6B;AACpD,IAAA,KAAA,MAAW,MAAA,IAAU,KAAK,GAAA,EAAK;AAC7B,MAAA,MAAM,QAAA,GAAW,UAAA,CAAW,GAAA,CAAI,MAAA,CAAO,QAAQ,CAAA;AAC/C,MAAA,IAAI,QAAA,KAAa,QAAW,UAAA,CAAW,GAAA,CAAI,OAAO,QAAA,EAAU,CAAC,MAAM,CAAC,CAAA;AAAA,WAC/D,QAAA,CAAS,KAAK,MAAM,CAAA;AAAA,IAC3B;AACA,IAAA,IAAA,CAAK,WAAA,GAAc,UAAA;AAAA,EACrB;AAAA;AAAA,EAGA,IAAI,SAAA,GAAsB;AACxB,IAAA,OAAO,CAAC,GAAG,IAAA,CAAK,YAAY,IAAA,EAAM,EAAE,IAAA,EAAK;AAAA,EAC3C;AAAA;AAAA,EAGA,IAAI,SAAA,GAAoB;AACtB,IAAA,OAAO,KAAK,GAAA,CAAI,MAAA;AAAA,EAClB;AAAA;AAAA,EAGA,IAAI,QAAA,EAA2B;AAC7B,IAAA,OAAO,IAAA,CAAK,WAAA,CAAY,GAAA,CAAI,QAAQ,CAAA;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,QAAA,EAA4C;AACtD,IAAA,OAAO,IAAA,CAAK,WAAA,CAAY,GAAA,CAAI,QA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;;;ACzIO,IAAM,OAAA,GAAkB","file":"index.cjs","sourcesContent":["// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Binding tables and textures, by semantic.\n *\n * A table or texture is declared under a name in the shader source, and that\n * name never reaches the linked program: GLSL ES 3.00 has no binding qualifier\n * for samplers, so the cross-compiler pairs each texture with a sampler and\n * names the combination itself — `u_maskLut` is declared, and what the program\n * carries is `SPIRV_Cross_Combinedu_maskLutSPIRV_Cross_DummySampler`.\n *\n * So the declared name is not what a consumer binds by. The semantic is. Each\n * envelope records, per emitted sampler uniform, the semantic it was built\n * from, the uniform the program actually has, and a texture unit assigned at\n * build. Bind the resource to that unit and set that uniform to it.\n */\n\nimport type { BindingRecord, LanguageBlock, ShaderStage } from \"./manifest.js\";\n\n/** Raised when a resource cannot be bound as asked. */\nexport class BindingError extends Error {\n override readonly name = \"BindingError\";\n}\n\n/**\n * One pipeline's sampler bindings, indexed by semantic.\n *\n * Built from the envelope's own `bindings`, which the build derived from the\n * emitted text rather than from the contract — so it describes the program\n * that exists, not the program that was intended.\n */\nexport class ResourceBindings {\n readonly #bySemantic: ReadonlyMap<string, readonly BindingRecord[]>;\n\n /** Every binding, in the order the envelope records them (units ascending). */\n readonly all: readonly BindingRecord[];\n\n constructor(block: LanguageBlock) {\n this.all = block.bindings ?? [];\n const bySemantic = new Map<string, BindingRecord[]>();\n for (const record of this.all) {\n const existing = bySemantic.get(record.semantic);\n if (existing === undefined) bySemantic.set(record.semantic, [record]);\n else existing.push(record);\n }\n this.#bySemantic = bySemantic;\n }\n\n /** Every semantic this pipeline binds, sorted. */\n get semantics(): string[] {\n return [...this.#bySemantic.keys()].sort();\n }\n\n /** How many texture units the pipeline spends in total. */\n get unitCount(): number {\n return this.all.length;\n }\n\n /** Whether the pipeline binds anything for `semantic`. */\n has(semantic: string): boolean {\n return this.#bySemantic.has(semantic);\n }\n\n /**\n * Every binding for `semantic` — more than one when the same resource is\n * read in both stages, which the build gives separate units.\n */\n forSemantic(semantic: string): readonly BindingRecord[] {\n return this.#bySemantic.get(semantic) ?? [];\n }\n\n /**\n * The one binding for `semantic`.\n *\n * @throws {BindingError} if the pipeline binds nothing for it, or binds it\n * in more than one stage — in which case use {@link forSemantic} and bind\n * each.\n */\n get(semantic: string): BindingRecord {\n const records = this.forSemantic(semantic);\n if (records.length === 1) return records[0] as BindingRecord;\n if (records.length === 0) {\n throw new BindingError(\n `this pipeline binds nothing for the semantic ${semantic}; it binds ${this.semantics.join(\", \") || \"nothing\"}.`,\n );\n }\n throw new BindingError(\n `${semantic} is bound in ${records.length} stages (${records.map((r) => r.stage).join(\", \")}); ` +\n \"use forSemantic() and bind each.\",\n );\n }\n\n /** Every binding a given stage spends a unit on. */\n forStage(stage: ShaderStage): readonly BindingRecord[] {\n return this.all.filter((record) => record.stage === stage);\n }\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * The uniform encodings the packer can write, and the check that a reflected\n * layout fits them.\n *\n * Internal: {@link UniformBlock} and {@link ShaderSet} share it, so an envelope\n * the set accepts is one the packer can write, and the two cannot disagree\n * about what an encoding is.\n *\n * Nothing here computes a std140 offset or size. The layout is the build's;\n * what is checked is only that the packer's own writes — `width` four-byte\n * components at the member's offset, or `order` sixteen-byte rows for a matrix,\n * or one element per `elementStride` for an array — land inside the extent the\n * build recorded for that member, and inside the block.\n */\n\nimport type { UniformLayout } from \"./manifest.js\";\n\n/** How a scalar component is stored. */\nexport type Kind = \"float\" | \"int\" | \"uint\";\n\n/** What one encoding means to the packer. */\nexport interface Encoding {\n readonly kind: Kind;\n /** Components per element: 1 for a scalar, 2–4 for a vector, order² for a matrix. */\n readonly width: number;\n /** The matrix order, for a matrix. */\n readonly order?: number;\n /** Whether the member is an array of these. */\n readonly isArray: boolean;\n}\n\nconst ELEMENTS: Readonly<Record<string, Omit<Encoding, \"isArray\">>> = {\n float: { kind: \"float\", width: 1 },\n int: { kind: \"int\", width: 1 },\n uint: { kind: \"uint\", width: 1 },\n vec2: { kind: \"float\", width: 2 },\n vec3: { kind: \"float\", width: 3 },\n vec4: { kind: \"float\", width: 4 },\n ivec2: { kind: \"int\", width: 2 },\n ivec3: { kind: \"int\", width: 3 },\n ivec4: { kind: \"int\", width: 4 },\n uvec2: { kind: \"uint\", width: 2 },\n uvec3: { kind: \"uint\", width: 3 },\n uvec4: { kind: \"uint\", width: 4 },\n mat2: { kind: \"float\", width: 4, order: 2 },\n mat3: { kind: \"float\", width: 9, order: 3 },\n mat4: { kind: \"float\", width: 16, order: 4 },\n};\n\nconst ARRAY_SUFFIX = \"[]\";\n\n/** The encodings the packer writes, each also as an array. */\nexport const KNOWN_ENCODINGS: readonly string[] = Object.keys(ELEMENTS);\n\n/** What `encoding` means, or `undefined` if the packer does not know it. */\nexport function describeEncoding(encoding: string): Encoding | undefined {\n const isArray = encoding.endsWith(ARRAY_SUFFIX);\n const element = isArray ? encoding.slice(0, -ARRAY_SUFFIX.length) : encoding;\n // An own-property lookup: `in` would accept `toString` as an encoding.\n if (!Object.hasOwn(ELEMENTS, element)) return undefined;\n return { ...(ELEMENTS[element] as Omit<Encoding, \"isArray\">), isArray };\n}\n\nconst isWhole = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isInteger(value);\n\n/**\n * Why `layout` cannot be written into a block of `blockSize` bytes, or\n * `undefined` if it can.\n *\n * A member with a `null` encoding passes: it is part of the block and counts\n * towards its size, and the packer refuses only a write to it.\n */\nexport function layoutProblem(\n name: string,\n layout: UniformLayout,\n blockSize: number,\n): string | undefined {\n if (typeof layout !== \"object\" || layout === null) {\n return `${name} has no layout record.`;\n }\n const { offset, size, elementStride, encoding } = layout;\n if (!isWhole(offset) || offset < 0 || offset % 4 !== 0) {\n return `${name} is at offset ${String(offset)}, which is not a non-negative multiple of 4.`;\n }\n if (!isWhole(size) || size <= 0 || offset + size > blockSize) {\n return (\n `${name} occupies ${String(size)} byte(s) at offset ${offset}, which does not lie ` +\n `within the ${blockSize}-byte block.`\n );\n }\n if (encoding === null) return undefined;\n if (typeof encoding !== \"string\") {\n return `${name} has the encoding ${String(encoding)}, which is not a name.`;\n }\n const described = describeEncoding(encoding);\n if (described === undefined) {\n return (\n `${name} has the encoding ${encoding}, which the packer does not know; it writes ` +\n `${KNOWN_ENCODINGS.join(\", \")}, and arrays of them.`\n );\n }\n // How far the packer's writes reach for one element, from the element's\n // start: a matrix is `order` rows, each at a sixteen-byte slot.\n const reach =\n described.order === undefined\n ? described.width * 4\n : (described.order - 1) * 16 + described.order * 4;\n if (described.isArray) {\n if (!isWhole(elementStride) || elementStride <= 0 || elementStride % 4 !== 0) {\n return (\n `${name} is ${encoding}, but the build reports an element stride of ` +\n `${String(elementStride)}.`\n );\n }\n if (reach > elementStride || elementStride > size) {\n return `${name} is ${encoding} with ${size} byte(s) at a ${elementStride}-byte stride, which does not hold one element.`;\n }\n return undefined;\n }\n if (reach > size) {\n return `${name} is ${encoding}, which writes ${reach} byte(s), but the build gives it ${size}.`;\n }\n return undefined;\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * The artifact set's documents, as types.\n *\n * These mirror what `vcti-shader-foundry` emits — `registry.json` and one\n * envelope per pipeline — field for field. The foundry is the only thing that\n * produces them; nothing here re-declares a contract or invents a field. When\n * the emitted shape changes, {@link SCHEMA_VERSION} changes with it and a set\n * carrying an unknown version is refused rather than misread.\n */\n\n/** The emitted document shape this package understands. */\nexport const SCHEMA_VERSION = 3;\n\n/** A shader language an artifact set can carry. Only `glsl` is emitted today. */\nexport type ShaderLanguage = \"glsl\" | \"wgsl\";\n\n/** A stage of a pipeline. */\nexport type ShaderStage = \"vertex\" | \"fragment\";\n\n/** One vertex attribute the pipeline reads. */\nexport interface AttributeSpec {\n /** The name the attribute is declared under. */\n readonly name: string;\n /** Its GL type, e.g. `vec3`, `int`. */\n readonly type: string;\n /** What the attribute means — how a consumer matches its own buffer to it. */\n readonly semantic: string;\n}\n\n/** One uniform block member the pipeline reads. */\nexport interface UniformSpec {\n readonly name: string;\n /** Its GL type, e.g. `vec3`, `mat4`, `int`. */\n readonly type: string;\n /**\n * Named states for an integer selector, e.g. `u_colorSource`. The numbers\n * are append-only across releases (see the foundry's stability rules).\n */\n readonly namedValues?: Readonly<Record<string, number>>;\n}\n\n/** One fragment output. Its index in `outputs` is its location. */\nexport interface OutputSpec {\n readonly name: string;\n readonly type: string;\n /**\n * The attachment format the output requires, or `null` for no exact\n * requirement. `null` is a claim, not an omission.\n */\n readonly format: string | null;\n}\n\n/** A texture read at exact integer coordinates — a lookup table, not an image. */\nexport interface TableSpec {\n readonly name: string;\n readonly type: string;\n readonly format: string;\n readonly semantic: string;\n}\n\n/** An image sampled between texels. */\nexport interface TextureSpec {\n readonly name: string;\n readonly semantic: string;\n readonly kind: string;\n readonly component: string;\n readonly format: string;\n readonly requiresMipChain: boolean;\n /** The name of a sampler this contract declares. */\n readonly sampler: string;\n /** The semantic of a uv attribute this contract carries. */\n readonly uv: string;\n readonly selection: string;\n readonly neutral: readonly number[] | null;\n}\n\n/** Sampler state a texture is read through. */\nexport interface SamplerSpec {\n readonly name: string;\n readonly magFilter: string;\n readonly minFilter: string;\n readonly mipmapFilter: string;\n readonly wrapS: string;\n readonly wrapT: string;\n}\n\n/**\n * A pipeline's binding surface: everything a caller must match.\n *\n * Order is significant. A uniform block's member order determines its byte\n * offsets, which is why {@link RegistryEntry.contractSha256} is computed over\n * this document with its sequences left unsorted.\n */\nexport interface PipelineContract {\n readonly id: string;\n readonly capabilities: readonly string[];\n readonly inputs: readonly AttributeSpec[];\n readonly uniforms: readonly UniformSpec[];\n readonly outputs: readonly OutputSpec[];\n readonly tables: readonly TableSpec[];\n readonly textures: readonly TextureSpec[];\n readonly samplers: readonly SamplerSpec[];\n}\n\n/** Versions of the three executables that compiled a set. `null` where unread. */\nexport interface ToolchainInfo {\n readonly slangc: string | null;\n readonly spirvCross: string | null;\n readonly glslang: string | null;\n}\n\n/** What produced a set, and with what. */\nexport interface GeneratorInfo {\n readonly name: string;\n readonly version: string;\n readonly toolchain: ToolchainInfo | null;\n}\n\n/**\n * One index entry: enough to choose this pipeline, and where to go next.\n *\n * Not the contract. `contractSha256` names the envelope's content without\n * repeating it, so a fetched envelope can be checked against the entry that\n * pointed at it.\n */\nexport interface RegistryEntry {\n readonly id: string;\n readonly description: string;\n readonly capabilities: readonly string[];\n readonly contractSha256: string;\n /** The envelope's path within the set, relative and POSIX. */\n readonly envelope: string;\n}\n\n/** `registry.json`: the index a consumer selects from. */\nexport interface Registry {\n readonly schemaVersion: number;\n readonly generator: GeneratorInfo;\n /** The closed set of tags any pipeline in this set may declare. */\n readonly capabilityVocabulary: readonly string[];\n readonly pipelines: readonly RegistryEntry[];\n}\n\n/**\n * Where std140 placed one uniform block member.\n *\n * Read rather than recomputed: a second implementation of the padding rules is\n * a second thing to be wrong, and it would diverge silently — on one pipeline,\n * in one case, such as the sixteen-byte stride std140 gives the eight-byte\n * elements of a `vec2[72]`.\n */\nexport interface UniformLayout {\n /** Byte offset from the start of the block. */\n readonly offset: number;\n /** Total byte size, including any array padding. */\n readonly size: number;\n /**\n * Bytes between array elements. For a member that is not an array it is\n * what the reflection reports for its components: `4` for a vector, `0` for\n * a scalar or a matrix. The packer reads it only for an array.\n */\n readonly elementStride: number;\n /** The element type — `float`, `vec3`, `mat4`, `ivec2`. */\n readonly encoding: string | null;\n /** `row` or `column`, present only for a matrix. */\n readonly majorness?: \"row\" | \"column\";\n}\n\n/**\n * One emitted sampler uniform, and the resource it was built from.\n *\n * The seam the declared names do not cross: GLSL ES 3.00 has no binding\n * qualifier for samplers, so the cross-compiler pairs each texture with a\n * sampler and names the combination itself. A consumer binds by\n * {@link semantic}, then uses {@link uniform} and {@link unit}.\n */\nexport interface BindingRecord {\n /** The semantic of the table or texture this was built from. */\n readonly semantic: string;\n /** The declared name of that resource. It does not reach the program. */\n readonly texture: string;\n /**\n * The declared name of the sampler it was paired with, or `null` where the\n * contract declares none — a table read at exact texel coordinates is paired\n * with the cross-compiler's dummy sampler, which the contract never names.\n */\n readonly sampler: string | null;\n /** The uniform the emitted program actually declares. */\n readonly uniform: string;\n readonly component: string;\n readonly stage: ShaderStage;\n /** The texture unit to bind to, assigned deterministically at build. */\n readonly unit: number;\n}\n\n/** One stage's emitted source and its hash. */\nexport interface StageSource {\n readonly source: string;\n readonly sha256: string;\n}\n\n/** Everything about one pipeline in one language. */\nexport interface LanguageBlock {\n /**\n * The reflected size of the whole uniform block, which is larger than the\n * contract: the compiler emits its entire global block whatever entry point\n * is compiled, so an undeformed pipeline's GLSL still carries deform members\n * its contract does not list. Allocate this many bytes.\n */\n readonly blockSize: number;\n /** Placement of every member the block holds, by name. */\n readonly layout: Readonly<Record<string, UniformLayout>>;\n readonly bindings: readonly BindingRecord[];\n readonly stages: Readonly<Partial<Record<ShaderStage, StageSource>>>;\n}\n\n/**\n * One pipeline as a self-contained document: contract plus its shaders.\n *\n * The second projection of the manifest, for consumption rather than\n * selection. Fetching one is a single request that cannot arrive half-stale.\n */\nexport interface Envelope {\n readonly schemaVersion: number;\n readonly generator: GeneratorInfo;\n /** The contract, with the pipeline's description alongside it. */\n readonly pipeline: PipelineContract & { readonly description: string };\n readonly contractSha256: string;\n readonly languages: Readonly<Partial<Record<ShaderLanguage, LanguageBlock>>>;\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Reading an artifact set: where the documents come from, and what is checked.\n *\n * The set is two projections of one build. The index is fetched once, to list\n * what can be drawn; an envelope is fetched to draw one pipeline. {@link\n * ShaderSet} keeps that shape — the index eagerly, envelopes on demand and\n * cached — and makes the one check the split exists to enable: the envelope it\n * received carries the `contractSha256` the index entry that pointed at it\n * recorded.\n *\n * Where the bytes come from is a {@link ArtifactSource}, so the same set works\n * bundled, served over HTTP, or read from a directory on disk.\n */\n\nimport { layoutProblem } from \"./encoding.js\";\nimport type {\n Envelope,\n LanguageBlock,\n Registry,\n RegistryEntry,\n ShaderLanguage,\n} from \"./manifest.js\";\nimport { SCHEMA_VERSION } from \"./manifest.js\";\n\n/** Raised for any artifact set this package will not read. */\nexport class ShaderSetError extends Error {\n override readonly name = \"ShaderSetError\";\n}\n\n/**\n * Where an artifact set's documents come from.\n *\n * Two methods, because there are two documents. `readEnvelope` receives the\n * whole index entry rather than an id: the entry carries the envelope's path\n * within the set, which is the set's business and not the caller's to\n * reconstruct.\n */\nexport interface ArtifactSource {\n /** The parsed `registry.json`. */\n readRegistry(): Promise<unknown>;\n /** The parsed envelope the entry points at. */\n readEnvelope(entry: RegistryEntry): Promise<unknown>;\n}\n\n/**\n * The base URL as an absolute URL.\n *\n * A relative base such as `/shaders/` is what a page naturally writes, and\n * `new URL` alone refuses it. In a browser it is resolved against the page's\n * own location, as a link would be; where there is no location there is\n * nothing to resolve it against, and guessing one would fetch from somewhere\n * the caller did not name.\n */\nfunction absoluteBase(baseUrl: string | URL): URL {\n if (baseUrl instanceof URL) return new URL(baseUrl.href);\n if (URL.canParse(baseUrl)) return new URL(baseUrl);\n const here = (globalThis as { location?: { href?: unknown } }).location?.href;\n if (typeof here === \"string\" && URL.canParse(baseUrl, here)) return new URL(baseUrl, here);\n throw new ShaderSetError(\n `${JSON.stringify(baseUrl)} is not an absolute URL, and there is no page location to ` +\n \"resolve it against. Outside a browser, pass an absolute URL such as \" +\n \"https://host/shaders/.\",\n );\n}\n\n/**\n * Reads a set served over HTTP under one base URL.\n *\n * A relative `baseUrl` is resolved against `location.href` where there is one\n * — in a browser — and refused elsewhere.\n *\n * @throws {ShaderSetError} for a relative `baseUrl` with no page location.\n */\nexport function fetchSource(baseUrl: string | URL, init?: RequestInit): ArtifactSource {\n const base = absoluteBase(baseUrl);\n // A base URL naming a directory must end in a slash or the last segment is\n // replaced rather than appended to.\n if (!base.pathname.endsWith(\"/\")) base.pathname += \"/\";\n\n const read = async (path: string): Promise<unknown> => {\n const url = new URL(path, base);\n const response = await fetch(url, init);\n if (!response.ok) {\n throw new ShaderSetError(\n `fetching ${url.href} failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n };\n\n return {\n readRegistry: () => read(\"registry.json\"),\n readEnvelope: (entry) => read(entry.envelope),\n };\n}\n\n/**\n * Reads a set unpacked into a directory on disk.\n *\n * `node:fs` is imported when the source is first read rather than when this\n * module is loaded, so importing this package in a browser does not pull a\n * Node built-in into the bundle.\n */\nexport function fsSource(directory: string): ArtifactSource {\n const read = async (path: string): Promise<unknown> => {\n const [{ readFile }, { join }] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:path\"),\n ]);\n const full = join(directory, ...path.split(\"/\"));\n try {\n return JSON.parse(await readFile(full, \"utf8\"));\n } catch (cause) {\n throw new ShaderSetError(`reading ${full} failed: ${(cause as Error).message}`, { cause });\n }\n };\n\n return {\n readRegistry: () => read(\"registry.json\"),\n readEnvelope: (entry) => read(entry.envelope),\n };\n}\n\nfunction assertSchema(document: { schemaVersion?: unknown }, what: string): void {\n if (document.schemaVersion !== SCHEMA_VERSION) {\n throw new ShaderSetError(\n `${what} is schema version ${String(document.schemaVersion)}, and this package reads ` +\n `${SCHEMA_VERSION}. A document whose shape is not the one expected is refused rather ` +\n \"than read with its fields misinterpreted.\",\n );\n }\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Check a capability list is an array of distinct strings.\n *\n * A repeated tag is not harmless: the exact match compares sizes, and a list\n * of `a, a` has the length of `{a, b}`.\n */\nfunction assertTags(tags: unknown, what: string): void {\n if (!Array.isArray(tags) || !tags.every((tag) => typeof tag === \"string\")) {\n throw new ShaderSetError(`${what} is not an array of capability tags.`);\n }\n const repeated = tags.filter((tag, index) => tags.indexOf(tag) !== index);\n if (repeated.length > 0) {\n throw new ShaderSetError(`${what} repeats the tag(s) ${[...new Set(repeated)].join(\", \")}.`);\n }\n}\n\nfunction assertEntry(entry: unknown, index: number): void {\n if (!isObject(entry) || typeof entry.id !== \"string\") {\n throw new ShaderSetError(`registry.json pipeline ${index} has no id.`);\n }\n for (const field of [\"contractSha256\", \"envelope\"] as const) {\n if (typeof entry[field] !== \"string\") {\n throw new ShaderSetError(`registry.json entry ${entry.id} has no ${field}.`);\n }\n }\n assertTags(entry.capabilities, `the capabilities of registry.json entry ${entry.id}`);\n}\n\nfunction asRegistry(document: unknown): Registry {\n if (!isObject(document)) {\n throw new ShaderSetError(\"registry.json is not an object.\");\n }\n assertSchema(document, \"registry.json\");\n if (!Array.isArray(document.pipelines)) {\n throw new ShaderSetError(\"registry.json carries no pipelines array.\");\n }\n assertTags(document.capabilityVocabulary, \"the capabilityVocabulary of registry.json\");\n document.pipelines.forEach(assertEntry);\n const ids = (document.pipelines as RegistryEntry[]).map((entry) => entry.id);\n const repeated = ids.filter((id, index) => ids.indexOf(id) !== index);\n if (repeated.length > 0) {\n throw new ShaderSetError(`registry.json lists ${repeated.join(\", \")} more than once.`);\n }\n return document as unknown as Registry;\n}\n\n/**\n * Check one language block is something the packer and binder can use.\n *\n * The layout is checked against itself, not recomputed: each member must sit\n * at a four-byte-aligned offset, its recorded extent must lie inside the\n * recorded block size, and its encoding must be one the packer writes.\n */\nfunction assertLanguage(id: string, language: string, block: unknown): void {\n const where = `the ${language} block of the envelope for ${id}`;\n if (!isObject(block)) throw new ShaderSetError(`${where} is not an object.`);\n const { blockSize, layout, bindings, stages } = block;\n if (typeof blockSize !== \"number\" || !Number.isInteger(blockSize) || blockSize <= 0) {\n throw new ShaderSetError(`${where} reports a block size of ${String(blockSize)}.`);\n }\n if (!isObject(layout)) throw new ShaderSetError(`${where} carries no layout.`);\n for (const [name, member] of Object.entries(layout)) {\n const problem = layoutProblem(name, member as never, blockSize);\n if (problem !== undefined) throw new ShaderSetError(`in ${where}, ${problem}`);\n }\n if (!Array.isArray(bindings)) throw new ShaderSetError(`${where} carries no bindings.`);\n if (!isObject(stages)) throw new ShaderSetError(`${where} carries no stages.`);\n}\n\nfunction asEnvelope(document: unknown, entry: RegistryEntry): Envelope {\n if (typeof document !== \"object\" || document === null) {\n throw new ShaderSetError(`the envelope for ${entry.id} is not an object.`);\n }\n const envelope = document as Envelope;\n assertSchema(envelope, `the envelope for ${entry.id}`);\n if (envelope.pipeline?.id !== entry.id) {\n throw new ShaderSetError(\n `${entry.envelope} describes pipeline ${String(envelope.pipeline?.id)}, but the index ` +\n `points at it for ${entry.id}.`,\n );\n }\n // The whole reason the index carries a hash instead of the contract: an\n // envelope that is not the one the index sent us to would bind at the wrong\n // offsets and draw a wrong picture with no error anywhere.\n if (envelope.contractSha256 !== entry.contractSha256) {\n throw new ShaderSetError(\n `the envelope for ${entry.id} carries contract ${envelope.contractSha256}, but the index ` +\n `entry that pointed at it records ${entry.contractSha256}. The set is mixed: the index ` +\n \"and this envelope are from different builds.\",\n );\n }\n assertTags(envelope.pipeline.capabilities, `the capabilities in the envelope for ${entry.id}`);\n if (!isObject(envelope.languages)) {\n throw new ShaderSetError(`the envelope for ${entry.id} carries no languages.`);\n }\n for (const [language, block] of Object.entries(envelope.languages)) {\n assertLanguage(entry.id, language, block);\n }\n return envelope;\n}\n\n/**\n * One artifact set, opened.\n *\n * Holds the index and caches each envelope it has been asked for. Every\n * envelope it hands out has been checked against the entry that pointed at it.\n */\nexport class ShaderSet {\n readonly #source: ArtifactSource;\n readonly #entries: ReadonlyMap<string, RegistryEntry>;\n readonly #envelopes = new Map<string, Promise<Envelope>>();\n\n /** The index, as read. */\n readonly registry: Registry;\n\n private constructor(source: ArtifactSource, registry: Registry) {\n this.#source = source;\n this.registry = registry;\n this.#entries = new Map(registry.pipelines.map((entry) => [entry.id, entry]));\n }\n\n /** Read the index and open the set. */\n static async open(source: ArtifactSource): Promise<ShaderSet> {\n return new ShaderSet(source, asRegistry(await source.readRegistry()));\n }\n\n /** Every pipeline the set holds, in the order the index lists them. */\n get pipelines(): readonly RegistryEntry[] {\n return this.registry.pipelines;\n }\n\n /** The closed set of capability tags any pipeline here may declare. */\n get capabilityVocabulary(): readonly string[] {\n return this.registry.capabilityVocabulary;\n }\n\n /** The index entry for `id`. */\n entry(id: string): RegistryEntry {\n const entry = this.#entries.get(id);\n if (entry === undefined) {\n throw new ShaderSetError(`no pipeline ${id} in this set; it holds ${this.#entries.size}.`);\n }\n return entry;\n }\n\n /** The envelope for `id`, fetched once and cached. */\n async envelope(id: string): Promise<Envelope> {\n const entry = this.entry(id);\n let pending = this.#envelopes.get(id);\n if (pending === undefined) {\n pending = this.#source.readEnvelope(entry).then((document) => asEnvelope(document, entry));\n // A failed read must not be cached, or one network blip poisons the id\n // for the lifetime of the set.\n pending.catch(() => this.#envelopes.delete(id));\n this.#envelopes.set(id, pending);\n }\n return pending;\n }\n\n /** The envelope's block for one language; `glsl` unless asked otherwise. */\n static language(envelope: Envelope, language: ShaderLanguage = \"glsl\"): LanguageBlock {\n const block = Object.hasOwn(envelope.languages, language)\n ? envelope.languages[language]\n : undefined;\n if (block === undefined) {\n const carried = Object.keys(envelope.languages).join(\", \") || \"none\";\n throw new ShaderSetError(\n `the envelope for ${envelope.pipeline.id} carries no ${language}; it carries ${carried}.`,\n );\n }\n return block;\n }\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Writing the uniform block, at the offsets the build reported.\n *\n * Nothing here computes std140. The envelope carries the reflected placement\n * of every member and the size of the whole block, and this writes into that;\n * a second implementation of the padding rules would be a second thing to be\n * wrong and would diverge silently — on one pipeline, in one case, such as the\n * sixteen-byte stride std140 gives the four-byte elements of an `int[72]`.\n *\n * The block is larger than the contract. The compiler emits its entire global\n * uniform block whatever entry point was compiled, so an undeformed pipeline's\n * GLSL still declares the deform members its contract does not list. Allocate\n * {@link LanguageBlock.blockSize}; write what you have; leave the rest zero.\n */\n\nimport type { Kind } from \"./encoding.js\";\nimport { describeEncoding, layoutProblem } from \"./encoding.js\";\nimport type { LanguageBlock, UniformLayout } from \"./manifest.js\";\n\n/** Raised for a write this packer will not make. */\nexport class UniformPackError extends Error {\n override readonly name = \"UniformPackError\";\n}\n\n/** How a matrix's elements are ordered in memory. */\nexport type Majorness = \"row\" | \"column\";\n\nconst INT32_MIN = -(2 ** 31);\nconst INT32_MAX = 2 ** 31 - 1;\nconst UINT32_MAX = 2 ** 32 - 1;\n\n/** Why `value` cannot be stored as `kind`, or `undefined` if it can. */\nfunction scalarProblem(kind: Kind, value: number): string | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return \"not a finite number\";\n if (kind === \"float\") return undefined;\n if (!Number.isInteger(value)) return `not an integer, and the member is ${kind}`;\n if (kind === \"int\" && (value < INT32_MIN || value > INT32_MAX)) {\n return \"outside the 32-bit signed range\";\n }\n if (kind === \"uint\" && (value < 0 || value > UINT32_MAX)) {\n return \"outside the 32-bit unsigned range\";\n }\n return undefined;\n}\n\n/**\n * One pipeline's uniform block, allocated and writable by member name.\n *\n * Create one per draw target and reuse it: the buffer is the thing uploaded,\n * and rewriting a member in place is cheaper than rebuilding it. Members never\n * written stay zero, which is the off state every always-present feature\n * defines for itself — a plane count of zero, a scale of zero.\n *\n * ## Matrices, and why the transpose goes the other way\n *\n * Hand {@link UniformBlock.set} a conventional column-major matrix and the\n * shaders apply that matrix. Getting there takes two corrections that happen\n * to cancel, and only one of them is visible in the layout:\n *\n * 1. The block declares its matrices `row_major`, so each sixteen-byte slot\n * holds a **row** of the GLSL variable rather than a column.\n * 2. The features are authored in Slang, which multiplies the HLSL way round,\n * and the emitted GLSL keeps it — `position * u_mvpMatrix`, never\n * `u_mvpMatrix * position`. In GLSL `v * M` is `transpose(M) * v`, so the\n * transform a shader applies is the transpose of the matrix it is given.\n *\n * Reading the layout and ignoring the multiply order gives a transposed\n * camera. That is a rotation's inverse, so it survives casual inspection: an\n * identity is unchanged by it, and so are the front, back, top and bottom\n * views of a symmetric model. It shows up as left and right views that are\n * mirrored, and as translations that travel along the wrong axis.\n *\n * So a column-major input is written through **untransposed** into a\n * `row_major` block, and transposed into a `column_major` one — the opposite\n * of what point 1 alone would ask for. `majorness` still describes the input\n * array's own order and nothing else; it is not a way to ask for a transpose.\n */\nexport class UniformBlock {\n readonly #layout: Readonly<Record<string, UniformLayout>>;\n readonly #floats: Float32Array;\n readonly #ints: Int32Array;\n readonly #uints: Uint32Array;\n\n /** The bytes to upload. */\n readonly buffer: ArrayBuffer;\n\n constructor(block: LanguageBlock) {\n if (!Number.isInteger(block.blockSize) || block.blockSize <= 0) {\n throw new UniformPackError(\n `the envelope reports a block size of ${String(block.blockSize)}.`,\n );\n }\n // Every member is checked now, not when it is first written: a layout the\n // packer cannot honour is a property of the envelope, and an encoding it\n // does not know would otherwise be written as if it were one float.\n for (const [name, layout] of Object.entries(block.layout)) {\n const problem = layoutProblem(name, layout, block.blockSize);\n if (problem !== undefined) throw new UniformPackError(problem);\n }\n this.#layout = block.layout;\n this.buffer = new ArrayBuffer(block.blockSize);\n // Every member in the block is four-byte aligned, so three views over the\n // one buffer cover every encoding without a DataView's per-write cost.\n this.#floats = new Float32Array(this.buffer);\n this.#ints = new Int32Array(this.buffer);\n this.#uints = new Uint32Array(this.buffer);\n }\n\n /** The block's size in bytes. */\n get byteLength(): number {\n return this.buffer.byteLength;\n }\n\n /** Whether the block declares `name`. */\n has(name: string): boolean {\n return Object.hasOwn(this.#layout, name) && this.#layout[name]?.encoding != null;\n }\n\n /** Every member the block declares. */\n get members(): readonly string[] {\n return Object.keys(this.#layout);\n }\n\n /** Zero the whole block. */\n clear(): this {\n this.#floats.fill(0);\n return this;\n }\n\n #entry(name: string): { layout: UniformLayout; encoding: string } {\n const layout = Object.hasOwn(this.#layout, name) ? this.#layout[name] : undefined;\n if (layout === undefined) {\n throw new UniformPackError(\n `the uniform block declares no ${name}. It declares ${this.members.length} member(s); ` +\n \"a name absent here is either a typo or a uniform this pipeline does not carry.\",\n );\n }\n if (layout.encoding == null) {\n throw new UniformPackError(\n `${name} has no encoding the build could report, so its bytes would be a guess. It is ` +\n \"part of the block and counts towards its size, but it cannot be written.\",\n );\n }\n return { layout, encoding: layout.encoding };\n }\n\n #writeScalars(\n kind: Kind,\n at: number,\n values: ArrayLike<number>,\n count: number,\n name: string,\n ): void {\n for (let index = 0; index < count; index++) {\n const value = values[index] as number;\n const problem = scalarProblem(kind, value);\n if (problem !== undefined) {\n throw new UniformPackError(`${name}[${index}] is ${String(value)}, which is ${problem}.`);\n }\n const slot = at + index;\n if (kind === \"float\") this.#floats[slot] = value;\n else if (kind === \"int\") this.#ints[slot] = value;\n else this.#uints[slot] = value;\n }\n }\n\n /**\n * Write one member.\n *\n * Accepts what the member's shape needs: a number for a scalar, a flat array\n * of components for a vector or matrix, and either a flat array or an array\n * of elements for an array member.\n *\n * A matrix is taken as column-major — the order GL APIs and every mat4\n * library produce — and is written so that the emitted shaders apply *that*\n * transform. See {@link UniformBlock} on why the bytes that achieve it are\n * not the ones the block's `row_major` qualifier alone would suggest. Pass\n * `majorness: \"row\"` only when the input array is itself row-major.\n */\n set(\n name: string,\n value: number | boolean | ArrayLike<number> | ReadonlyArray<ArrayLike<number>>,\n options?: { majorness?: Majorness },\n ): this {\n const { layout, encoding } = this.#entry(name);\n // Checked when the block was built, so the encoding is known.\n const { kind, width, order, isArray } = describeEncoding(encoding) as NonNullable<\n ReturnType<typeof describeEncoding>\n >;\n\n if (typeof value === \"boolean\") value = value ? 1 : 0;\n\n if (typeof value === \"number\") {\n if (isArray || width !== 1) {\n throw new UniformPackError(`${name} is ${encoding}; a single number cannot fill it.`);\n }\n this.#writeScalars(kind, layout.offset / 4, [value], 1, name);\n return this;\n }\n\n // An array of arrays is flattened to its components; anything else is\n // already flat. Doing this once keeps the width checks below in one place.\n const flat: number[] | ArrayLike<number> =\n value.length > 0 && typeof (value as ReadonlyArray<ArrayLike<number>>)[0] === \"object\"\n ? (value as ReadonlyArray<ArrayLike<number>>).flatMap((item) => Array.from(item))\n : (value as ArrayLike<number>);\n\n if (order !== undefined) {\n if (isArray)\n throw new UniformPackError(`${name} is an array of matrices, which is not supported.`);\n this.#setMatrix(name, layout, order, flat, options?.majorness ?? \"column\");\n return this;\n }\n\n if (!isArray) {\n if (flat.length !== width) {\n throw new UniformPackError(\n `${name} is ${encoding} and needs ${width} component(s); got ${flat.length}.`,\n );\n }\n this.#writeScalars(kind, layout.offset / 4, flat, width, name);\n return this;\n }\n\n // An array member's elements sit at elementStride bytes apart, which for a\n // vec2[] or an int[] is padding, not packing: std140 rounds every array\n // element up to sixteen bytes.\n // The stride was checked when the block was built: a positive multiple of\n // four that holds one element.\n const stride = layout.elementStride;\n const capacity = Math.floor(layout.size / stride);\n if (flat.length % width !== 0) {\n throw new UniformPackError(\n `${name} is ${encoding}; ${flat.length} value(s) is not a whole number of ${width}-component elements.`,\n );\n }\n const count = flat.length / width;\n if (count > capacity) {\n throw new UniformPackError(`${name} holds ${capacity} element(s); got ${count}.`);\n }\n for (let index = 0; index < count; index++) {\n const at = (layout.offset + index * stride) / 4;\n this.#writeScalars(\n kind,\n at,\n Array.prototype.slice.call(flat, index * width, (index + 1) * width),\n width,\n name,\n );\n }\n return this;\n }\n\n #setMatrix(\n name: string,\n layout: UniformLayout,\n order: number,\n values: ArrayLike<number>,\n given: Majorness,\n ): void {\n if (values.length !== order * order) {\n throw new UniformPackError(\n `${name} is mat${order} and needs ${order * order} values; got ${values.length}.`,\n );\n }\n // Whatever its majorness, a matrix is stored as `order` rows or columns of\n // sixteen bytes each — std140 gives every one of them a vec4's alignment.\n const wanted = layout.majorness ?? \"column\";\n const base = layout.offset / 4;\n for (let major = 0; major < order; major++) {\n for (let minor = 0; minor < order; minor++) {\n // Reading index (minor, major) from the input in its own order, and\n // writing it to slot `major` of the block's order.\n //\n // Transposing when the two orders *agree* looks backwards and is the\n // whole point: the shaders multiply row-vector-first, so the matrix\n // they apply is already the transpose of the one they are handed, and\n // the storage order has to undo that rather than compound it. The\n // class comment works it through.\n const source = wanted === given ? minor * order + major : major * order + minor;\n const value = values[source] as number;\n if (scalarProblem(\"float\", value) !== undefined) {\n throw new UniformPackError(\n `${name}[${source}] is ${String(value)}, which is not a finite number.`,\n );\n }\n this.#floats[base + major * 4 + minor] = value;\n }\n }\n }\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Choosing a pipeline.\n *\n * A pipeline's id names its vertex variant and its fragment shape; its\n * capability set is what a consumer matches on. The match is **exact**: a\n * capability set is a description of what the pipeline does, not a list of\n * minimum requirements, and a pipeline carrying a capability you did not ask\n * for will read an attribute you did not bind.\n *\n * Nothing here ranks. The artifact set carries no defaults, no preference\n * order and no fallbacks, and inventing one in this package would make it a\n * policy every consumer inherits without asking. What is here is the exact\n * match, and the filters a caller needs to build its own choice.\n */\n\nimport type { Registry, RegistryEntry } from \"./manifest.js\";\n\n/** Raised when a request cannot be resolved to one pipeline. */\nexport class PipelineSelectionError extends Error {\n override readonly name = \"PipelineSelectionError\";\n}\n\nconst asSet = (tags: Iterable<string>): ReadonlySet<string> => new Set(tags);\n\nfunction sameSet(a: ReadonlySet<string>, b: readonly string[]): boolean {\n // Compared as sets on both sides: a list that repeats a tag must not pass\n // for a larger set on length alone. A loaded set refuses repeats anyway;\n // this keeps the match exact for entries built by hand.\n const other = asSet(b);\n if (a.size !== other.size) return false;\n for (const tag of other) if (!a.has(tag)) return false;\n return true;\n}\n\n/**\n * Check every tag against the set's own vocabulary.\n *\n * The vocabulary is closed per document, so a tag outside it can never match\n * anything. Catching that here names the typo; leaving it to\n * {@link matchCapabilities} would report only that nothing matched.\n */\nexport function validateCapabilities(registry: Registry, capabilities: Iterable<string>): void {\n const vocabulary = new Set(registry.capabilityVocabulary);\n const unknown = [...asSet(capabilities)].filter((tag) => !vocabulary.has(tag));\n if (unknown.length > 0) {\n throw new PipelineSelectionError(\n `capability tag(s) not in this set's vocabulary: ${unknown.join(\", \")}. The vocabulary is ` +\n `closed, so no pipeline here can carry them. It holds: ${registry.capabilityVocabulary.join(\", \")}.`,\n );\n }\n}\n\n/** Every pipeline whose capability set is exactly `capabilities`. */\nexport function matchCapabilities(\n entries: readonly RegistryEntry[],\n capabilities: Iterable<string>,\n): RegistryEntry[] {\n const wanted = asSet(capabilities);\n return entries.filter((entry) => sameSet(wanted, entry.capabilities));\n}\n\n/**\n * The one pipeline whose capability set is exactly `capabilities`.\n *\n * @throws {PipelineSelectionError} if none matches, or more than one does —\n * an ambiguous match is a set whose matrix has two pipelines with the same\n * capabilities, which is a question for the builder, not something to\n * resolve by picking the first.\n */\nexport function resolvePipeline(\n registry: Registry,\n capabilities: Iterable<string>,\n): RegistryEntry {\n validateCapabilities(registry, capabilities);\n const wanted = [...asSet(capabilities)].sort();\n const matches = matchCapabilities(registry.pipelines, wanted);\n if (matches.length === 1) return matches[0] as RegistryEntry;\n if (matches.length === 0) {\n throw new PipelineSelectionError(\n `no pipeline in this set has exactly the capabilities {${wanted.join(\", \")}}. The match is ` +\n \"exact: a pipeline carrying a capability you did not ask for reads an attribute you did \" +\n \"not bind.\",\n );\n }\n throw new PipelineSelectionError(\n `${matches.length} pipelines share the capabilities {${wanted.join(\", \")}}: ` +\n `${matches.map((entry) => entry.id).join(\", \")}.`,\n );\n}\n\n/** Every pipeline carrying all of `capabilities`, whatever else it carries. */\nexport function withCapabilities(\n entries: readonly RegistryEntry[],\n capabilities: Iterable<string>,\n): RegistryEntry[] {\n const wanted = [...asSet(capabilities)];\n return entries.filter((entry) => wanted.every((tag) => entry.capabilities.includes(tag)));\n}\n\n/**\n * Every tag any of `entries` declares, sorted.\n *\n * For building a chooser: the vocabulary is what the features offer, this is\n * what this set actually reaches.\n */\nexport function capabilitiesInUse(entries: readonly RegistryEntry[]): string[] {\n return [...new Set(entries.flatMap((entry) => [...entry.capabilities]))].sort();\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Reading back a pick texel.\n *\n * The pick pass writes per-pixel identifiers into an integer attachment\n * instead of a color. Four unsigned 32-bit channels: the primitive id, the\n * view depth, and two reserved. Decoding them is arithmetic, not GPU work, so\n * it lives here rather than in a renderer — a WebGPU consumer reads the same\n * texel and must read it the same way.\n *\n * **Three things about the layout are easy to get wrong, and two fail\n * silently**, which is why this is written once:\n *\n * - The depth channel holds the *bits* of a `float32`, not a number. Read as\n * an integer it is a value in the billions.\n * - A pixel where nothing was drawn carries {@link PICK_EMPTY} in every\n * channel, and emptiness must be tested on the identifier — a reserved\n * channel works today and stops working the moment one is claimed.\n * - The target must be cleared to {@link PICK_EMPTY} before the pass. Cleared\n * to zero, every empty pixel decodes as primitive 0.\n *\n * The layout is the `pick` feature's, mirrored from its Python.\n */\n\nimport type { Registry, RegistryEntry } from \"./manifest.js\";\nimport { PipelineSelectionError, withCapabilities } from \"./select.js\";\n\n/** The capability tag a pick pipeline declares. */\nexport const PICK_CAPABILITY = \"pick\";\n\n/**\n * The value every channel carries where no geometry was drawn, and what the\n * target is cleared to before the pass.\n */\nexport const PICK_EMPTY = 0xffffffff;\n\n/** What a fragment writes into each reserved channel. */\nexport const PICK_RESERVED = 0;\n\n/** What each channel of the texel holds, in order. */\nexport const PICK_CHANNELS = [\"primitiveId\", \"depth\", \"reserved0\", \"reserved1\"] as const;\n\n/**\n * The capability tags that change where the vertex stage puts geometry. A pick\n * pipeline must carry each one its color pipeline carries: these are not\n * optional extras a smaller pick pipeline may leave out.\n */\nconst DEFORM_CAPABILITIES = [\"deform3\", \"deform6\"] as const;\n\n/** What one pick texel identifies. */\nexport interface Pick {\n /** The primitive id the fragment carried, as the caller's data set it. */\n readonly primitiveId: number;\n /**\n * Distance along the camera's forward axis — `-z` in view space, not a\n * normalized depth. The caller owns the ray, so a depth is enough to place\n * the point and costs one channel where a position would cost three.\n */\n readonly depth: number;\n}\n\n/** Raised for a texel that cannot have come from a pick pass. */\nexport class PickDecodeError extends Error {\n override readonly name = \"PickDecodeError\";\n}\n\n// One buffer, reused: the depth channel is a reinterpretation, so the bits go\n// in as an unsigned integer and come out as the float they always were.\nconst scratch = new ArrayBuffer(4);\nconst asUint = new Uint32Array(scratch);\nconst asFloat = new Float32Array(scratch);\n\n/**\n * Decode one texel of a pick readback, or `null` where nothing was drawn.\n *\n * @param texel the four channel values, as unsigned 32-bit integers — four\n * elements of the `Uint32Array` a `readPixels` of an `rgba32ui` attachment\n * fills, at the offset of the pixel wanted.\n * @throws {PickDecodeError} if a channel does not fit in 32 bits, which means\n * the readback was decoded at the wrong width and every field is suspect.\n */\nexport function decodePick(texel: ArrayLike<number>, offset = 0): Pick | null {\n if (texel.length - offset < 4) {\n throw new PickDecodeError(\n `a pick texel is 4 channels; ${texel.length - offset} are available from offset ${offset}.`,\n );\n }\n for (let channel = 0; channel < 4; channel++) {\n const value = texel[offset + channel] as number;\n if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {\n throw new PickDecodeError(\n `the ${PICK_CHANNELS[channel]} channel is ${String(value)}, which is not a 32-bit unsigned ` +\n \"integer. The readback was decoded at the wrong width, so every field is suspect.\",\n );\n }\n }\n\n const primitiveId = texel[offset] as number;\n // Tested on the identifier, never on a reserved channel.\n if (primitiveId === PICK_EMPTY) return null;\n\n asUint[0] = texel[offset + 1] as number;\n return { primitiveId, depth: asFloat[0] as number };\n}\n\n/**\n * The pick pipeline that matches a color pipeline.\n *\n * Picking is a second draw of the same geometry, so the two passes must agree\n * on everything the vertex stage does — above all the deform variant, or\n * deformed geometry is picked where it is not drawn.\n *\n * Found by capability: a pick pipeline is compatible when it asks for nothing\n * the color pass does not already have, and carries the color pipeline's\n * deform variant (`deform3` or `deform6`) — the one difference that would put\n * picked geometry somewhere other than where it is drawn, so it is required\n * rather than preferred. Of the compatible ones, the one carrying the most\n * capabilities keeps the most of the vertex stage in step.\n *\n * @throws {PipelineSelectionError} if the set has no compatible pick pipeline\n * — including when it has pick pipelines, but none with the color\n * pipeline's deform variant — or two equally good ones.\n */\nexport function pickPipelineFor(registry: Registry, color: RegistryEntry): RegistryEntry {\n const available = new Set<string>([...color.capabilities, PICK_CAPABILITY]);\n const deform = DEFORM_CAPABILITIES.filter((tag) => available.has(tag));\n const compatible = withCapabilities(registry.pipelines, [PICK_CAPABILITY, ...deform]).filter(\n (entry) => entry.capabilities.every((tag) => available.has(tag)),\n );\n if (compatible.length === 0) {\n const variant = deform.length > 0 ? ` carrying ${deform.join(\", \")}` : \"\";\n throw new PipelineSelectionError(\n `this set has no pick pipeline${variant} compatible with ${color.id}. Picking draws the ` +\n \"same geometry a second time, so it needs a pick pipeline whose vertex stage matches.\",\n );\n }\n const best = Math.max(...compatible.map((entry) => entry.capabilities.length));\n const winners = compatible.filter((entry) => entry.capabilities.length === best);\n if (winners.length > 1) {\n throw new PipelineSelectionError(\n `${color.id} has ${winners.length} equally compatible pick pipelines: ` +\n `${winners.map((entry) => entry.id).join(\", \")}.`,\n );\n }\n return winners[0] as RegistryEntry;\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n// __PKG_VERSION__ is replaced with the package.json version at build time by\n// tsup (see tsup.config.ts) and by vitest during tests (see vitest.config.ts).\n// package.json remains the single source of truth; it stays out of the TS\n// program so tsc can emit declarations cleanly (see tsconfig.build.json).\ndeclare const __PKG_VERSION__: string;\n\n/** The package version, injected from package.json at build time. */\nexport const VERSION: string = __PKG_VERSION__;\n"]}
1
+ {"version":3,"sources":["../src/bind.ts","../src/blocks.ts","../src/encoding.ts","../src/manifest.ts","../src/load.ts","../src/pack.ts","../src/select.ts","../src/pick.ts","../src/version.ts"],"names":[],"mappings":";;;AAqBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EACpB,IAAA,GAAO,cAAA;AAC3B;AASO,IAAM,mBAAN,MAAuB;AAAA,EACnB,WAAA;AAAA;AAAA,EAGA,GAAA;AAAA,EAET,YAAY,KAAA,EAAsB;AAChC,IAAA,IAAA,CAAK,GAAA,GAAM,KAAA,CAAM,QAAA,IAAY,EAAC;AAC9B,IAAA,MAAM,UAAA,uBAAiB,GAAA,EAA6B;AACpD,IAAA,KAAA,MAAW,MAAA,IAAU,KAAK,GAAA,EA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AA,CAAK,GAAA,CAAI,GAAG,UAAA,CAAW,GAAA,CAAI,CAAC,KAAA,KAAU,KAAA,CAAM,YAAA,CAAa,MAAM,CAAC,CAAA;AAC7E,EAAA,MAAM,OAAA,GAAU,WAAW,MAAA,CAAO,CAAC,UAAU,KAAA,CAAM,YAAA,CAAa,WAAW,IAAI,CAAA;AAC/E,EAAA,IAAI,OAAA,CAAQ,SAAS,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,sBAAA;AAAA,MACR,GAAG,KAAA,CAAM,EAAE,CAAA,KAAA,EAAQ,OAAA,CAAQ,MAAM,CAAA,oCAAA,EAC5B,OAAA,CAAQ,GAAA,CAAI,CAAC,UAAU,KAAA,CAAM,EAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KAClD;AAAA,EACF;AACA,EAAA,OAAO,QAAQ,CAAC,CAAA;AAClB;;;ACpJO,IAAM,OAAA,GAAkB","file":"index.cjs","sourcesContent":["// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Binding tables and textures, by semantic.\n *\n * A table or texture is declared under a name in the shader source, and that\n * name never reaches the linked program: GLSL ES 3.00 has no binding qualifier\n * for samplers, so the cross-compiler pairs each texture with a sampler and\n * names the combination itself — `u_maskLut` is declared, and what the program\n * carries is `SPIRV_Cross_Combinedu_maskLutSPIRV_Cross_DummySampler`.\n *\n * So the declared name is not what a consumer binds by. The semantic is. Each\n * envelope records, per emitted sampler uniform, the semantic it was built\n * from, the uniform the program actually has, and a texture unit assigned at\n * build. Bind the resource to that unit and set that uniform to it.\n */\n\nimport type { BindingRecord, LanguageBlock, ShaderStage } from \"./manifest.js\";\n\n/** Raised when a resource cannot be bound as asked. */\nexport class BindingError extends Error {\n override readonly name = \"BindingError\";\n}\n\n/**\n * One pipeline's sampler bindings, indexed by semantic.\n *\n * Built from the envelope's own `bindings`, which the build derived from the\n * emitted text rather than from the contract — so it describes the program\n * that exists, not the program that was intended.\n */\nexport class ResourceBindings {\n readonly #bySemantic: ReadonlyMap<string, readonly BindingRecord[]>;\n\n /** Every binding, in the order the envelope records them (units ascending). */\n readonly all: readonly BindingRecord[];\n\n constructor(block: LanguageBlock) {\n this.all = block.bindings ?? [];\n const bySemantic = new Map<string, BindingRecord[]>();\n for (const record of this.all) {\n const existing = bySemantic.get(record.semantic);\n if (existing === undefined) bySemantic.set(record.semantic, [record]);\n else existing.push(record);\n }\n this.#bySemantic = bySemantic;\n }\n\n /** Every semantic this pipeline binds, sorted. */\n get semantics(): string[] {\n return [...this.#bySemantic.keys()].sort();\n }\n\n /** How many texture units the pipeline spends in total. */\n get unitCount(): number {\n return this.all.length;\n }\n\n /** Whether the pipeline binds anything for `semantic`. */\n has(semantic: string): boolean {\n return this.#bySemantic.has(semantic);\n }\n\n /**\n * Every binding for `semantic` — more than one when the same resource is\n * read in both stages, which the build gives separate units.\n */\n forSemantic(semantic: string): readonly BindingRecord[] {\n return this.#bySemantic.get(semantic) ?? [];\n }\n\n /**\n * The one binding for `semantic`.\n *\n * @throws {BindingError} if the pipeline binds nothing for it, or binds it\n * in more than one stage — in which case use {@link forSemantic} and bind\n * each.\n */\n get(semantic: string): BindingRecord {\n const records = this.forSemantic(semantic);\n if (records.length === 1) return records[0] as BindingRecord;\n if (records.length === 0) {\n throw new BindingError(\n `this pipeline binds nothing for the semantic ${semantic}; it binds ${this.semantics.join(\", \") || \"nothing\"}.`,\n );\n }\n throw new BindingError(\n `${semantic} is bound in ${records.length} stages (${records.map((r) => r.stage).join(\", \")}); ` +\n \"use forSemantic() and bind each.\",\n );\n }\n\n /** Every binding a given stage spends a unit on. */\n forStage(stage: ShaderStage): readonly BindingRecord[] {\n return this.all.filter((record) => record.stage === stage);\n }\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Giving each occurrence of a mesh its own rows of a scene table.\n *\n * A slab's atom ids are local to its mesh: `0 … n-1` in every slab. Two\n * occurrences of one mesh drawn from one vertex buffer would read the same\n * mask rows and pick as the same thing. The per-draw base uniforms solve that\n * on the GPU — the shader reads row `a_atomId + u_maskLutBase` — and the pick\n * pass writes that sum as the group id. What is left is bookkeeping on the\n * CPU: hand each occurrence a block of rows that no other occurrence uses, set\n * its base before its draw, and turn a picked group id back into the\n * occurrence and the mesh-local atom. This does that bookkeeping, once.\n *\n * It is append-only. A scene that drops occurrences rebuilds its blocks (and\n * its table) rather than leaving holes to be reused, which keeps a group id\n * meaning one thing for as long as the table it indexes is the same.\n */\n\n/** Raised for a block that cannot be given out. */\nexport class TableBlockError extends Error {\n override readonly name = \"TableBlockError\";\n}\n\n/** One row of a scene table, found by {@link TableBlocks.locate}. */\nexport interface BlockRow<T> {\n /** Whoever the block was given to: an occurrence, as the caller names it. */\n readonly owner: T;\n /** The block's first row: the base its draws are made with. */\n readonly base: number;\n /** The row within the block: the mesh-local id, `row - base`. */\n readonly offset: number;\n}\n\n/** The largest row count a block or a table may reach: the shader's `int`. */\nconst INT_ROWS = 2 ** 31;\n\n/**\n * Contiguous blocks of rows in one scene table, given out in order.\n *\n * ```ts\n * const blocks = new TableBlocks<Occurrence>();\n * for (const occurrence of scene) occurrence.maskBase = blocks.allocate(mesh.atomCount, occurrence);\n * // …build the scene mask, blocks.rows rows, each occurrence's at its base…\n * const hit = pass.pick(x, y, drawScene);\n * const found = hit && blocks.locate(hit.groupId); // { owner, base, offset }\n * ```\n */\nexport class TableBlocks<T = unknown> {\n readonly #bases: number[] = [];\n readonly #owners: T[] = [];\n #rows = 0;\n\n /** The most rows the table may hold. */\n readonly maxRows: number;\n\n /**\n * @param options.maxRows the most rows the table may hold — the capacity of\n * the texture it will be uploaded to, say. At most, and by default, 2³¹:\n * the shader adds the base to an `int`.\n * @throws {TableBlockError} if `maxRows` is not a positive integer no larger\n * than 2³¹.\n */\n constructor(options: { maxRows?: number } = {}) {\n const maxRows = options.maxRows ?? INT_ROWS;\n if (!Number.isInteger(maxRows) || maxRows < 1 || maxRows > INT_ROWS) {\n throw new TableBlockError(\n `maxRows is ${String(maxRows)}; it must be a positive integer no larger than 2^31`,\n );\n }\n this.maxRows = maxRows;\n }\n\n /** Rows given out so far: the size the table must be. */\n get rows(): number {\n return this.#rows;\n }\n\n /** How many blocks have been given out. */\n get size(): number {\n return this.#bases.length;\n }\n\n /**\n * Give out the next `rows` rows.\n *\n * @returns the block's base: the uniform to draw the owner with, and where\n * its rows start in the table.\n * @throws {TableBlockError} if `rows` is not a positive integer, or the\n * table would grow past {@link maxRows}. Nothing is given out then.\n */\n allocate(rows: number, owner: T): number {\n if (!Number.isInteger(rows) || rows < 1) {\n throw new TableBlockError(`a block is a positive whole number of rows, not ${String(rows)}`);\n }\n if (this.#rows + rows > this.maxRows) {\n throw new TableBlockError(\n `${rows} rows at ${this.#rows} would take the table past its ${this.maxRows} rows`,\n );\n }\n const base = this.#rows;\n this.#bases.push(base);\n this.#owners.push(owner);\n this.#rows += rows;\n return base;\n }\n\n /**\n * The block a row falls in — a picked `groupId`, say — or `null` when no\n * block holds it.\n */\n locate(row: number): BlockRow<T> | null {\n if (!Number.isInteger(row) || row < 0 || row >= this.#rows) return null;\n // The bases are ascending: find the last one at or below the row.\n let low = 0;\n let high = this.#bases.length - 1;\n while (low < high) {\n const middle = Math.floor((low + high + 1) / 2);\n if ((this.#bases[middle] as number) <= row) low = middle;\n else high = middle - 1;\n }\n const base = this.#bases[low] as number;\n return { owner: this.#owners[low] as T, base, offset: row - base };\n }\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * The uniform encodings the packer can write, and the check that a reflected\n * layout fits them.\n *\n * Internal: {@link UniformBlock} and {@link ShaderSet} share it, so an envelope\n * the set accepts is one the packer can write, and the two cannot disagree\n * about what an encoding is.\n *\n * Nothing here computes a std140 offset or size. The layout is the build's;\n * what is checked is only that the packer's own writes — `width` four-byte\n * components at the member's offset, or `order` sixteen-byte rows for a matrix,\n * or one element per `elementStride` for an array — land inside the extent the\n * build recorded for that member, and inside the block.\n */\n\nimport type { UniformLayout } from \"./manifest.js\";\n\n/** How a scalar component is stored. */\nexport type Kind = \"float\" | \"int\" | \"uint\";\n\n/** What one encoding means to the packer. */\nexport interface Encoding {\n readonly kind: Kind;\n /** Components per element: 1 for a scalar, 2–4 for a vector, order² for a matrix. */\n readonly width: number;\n /** The matrix order, for a matrix. */\n readonly order?: number;\n /** Whether the member is an array of these. */\n readonly isArray: boolean;\n}\n\nconst ELEMENTS: Readonly<Record<string, Omit<Encoding, \"isArray\">>> = {\n float: { kind: \"float\", width: 1 },\n int: { kind: \"int\", width: 1 },\n uint: { kind: \"uint\", width: 1 },\n vec2: { kind: \"float\", width: 2 },\n vec3: { kind: \"float\", width: 3 },\n vec4: { kind: \"float\", width: 4 },\n ivec2: { kind: \"int\", width: 2 },\n ivec3: { kind: \"int\", width: 3 },\n ivec4: { kind: \"int\", width: 4 },\n uvec2: { kind: \"uint\", width: 2 },\n uvec3: { kind: \"uint\", width: 3 },\n uvec4: { kind: \"uint\", width: 4 },\n mat2: { kind: \"float\", width: 4, order: 2 },\n mat3: { kind: \"float\", width: 9, order: 3 },\n mat4: { kind: \"float\", width: 16, order: 4 },\n};\n\nconst ARRAY_SUFFIX = \"[]\";\n\n/** The encodings the packer writes, each also as an array. */\nexport const KNOWN_ENCODINGS: readonly string[] = Object.keys(ELEMENTS);\n\n/** What `encoding` means, or `undefined` if the packer does not know it. */\nexport function describeEncoding(encoding: string): Encoding | undefined {\n const isArray = encoding.endsWith(ARRAY_SUFFIX);\n const element = isArray ? encoding.slice(0, -ARRAY_SUFFIX.length) : encoding;\n // An own-property lookup: `in` would accept `toString` as an encoding.\n if (!Object.hasOwn(ELEMENTS, element)) return undefined;\n return { ...(ELEMENTS[element] as Omit<Encoding, \"isArray\">), isArray };\n}\n\nconst isWhole = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isInteger(value);\n\n/**\n * Why `layout` cannot be written into a block of `blockSize` bytes, or\n * `undefined` if it can.\n *\n * A member with a `null` encoding passes: it is part of the block and counts\n * towards its size, and the packer refuses only a write to it.\n */\nexport function layoutProblem(\n name: string,\n layout: UniformLayout,\n blockSize: number,\n): string | undefined {\n if (typeof layout !== \"object\" || layout === null) {\n return `${name} has no layout record.`;\n }\n const { offset, size, elementStride, encoding } = layout;\n if (!isWhole(offset) || offset < 0 || offset % 4 !== 0) {\n return `${name} is at offset ${String(offset)}, which is not a non-negative multiple of 4.`;\n }\n if (!isWhole(size) || size <= 0 || offset + size > blockSize) {\n return (\n `${name} occupies ${String(size)} byte(s) at offset ${offset}, which does not lie ` +\n `within the ${blockSize}-byte block.`\n );\n }\n if (encoding === null) return undefined;\n if (typeof encoding !== \"string\") {\n return `${name} has the encoding ${String(encoding)}, which is not a name.`;\n }\n const described = describeEncoding(encoding);\n if (described === undefined) {\n return (\n `${name} has the encoding ${encoding}, which the packer does not know; it writes ` +\n `${KNOWN_ENCODINGS.join(\", \")}, and arrays of them.`\n );\n }\n // How far the packer's writes reach for one element, from the element's\n // start: a matrix is `order` rows, each at a sixteen-byte slot.\n const reach =\n described.order === undefined\n ? described.width * 4\n : (described.order - 1) * 16 + described.order * 4;\n if (described.isArray) {\n if (!isWhole(elementStride) || elementStride <= 0 || elementStride % 4 !== 0) {\n return (\n `${name} is ${encoding}, but the build reports an element stride of ` +\n `${String(elementStride)}.`\n );\n }\n if (reach > elementStride || elementStride > size) {\n return `${name} is ${encoding} with ${size} byte(s) at a ${elementStride}-byte stride, which does not hold one element.`;\n }\n return undefined;\n }\n if (reach > size) {\n return `${name} is ${encoding}, which writes ${reach} byte(s), but the build gives it ${size}.`;\n }\n return undefined;\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * The artifact set's documents, as types.\n *\n * These mirror what `vcti-shader-foundry` emits — `registry.json` and one\n * envelope per pipeline — field for field. The foundry is the only thing that\n * produces them; nothing here re-declares a contract or invents a field. When\n * the emitted shape changes, {@link SCHEMA_VERSION} changes with it and a set\n * carrying an unknown version is refused rather than misread.\n */\n\n/** The emitted document shape this package understands. */\nexport const SCHEMA_VERSION = 3;\n\n/** A shader language an artifact set can carry. Only `glsl` is emitted today. */\nexport type ShaderLanguage = \"glsl\" | \"wgsl\";\n\n/** A stage of a pipeline. */\nexport type ShaderStage = \"vertex\" | \"fragment\";\n\n/** One vertex attribute the pipeline reads. */\nexport interface AttributeSpec {\n /** The name the attribute is declared under. */\n readonly name: string;\n /** Its GL type, e.g. `vec3`, `int`. */\n readonly type: string;\n /** What the attribute means — how a consumer matches its own buffer to it. */\n readonly semantic: string;\n}\n\n/** One uniform block member the pipeline reads. */\nexport interface UniformSpec {\n readonly name: string;\n /** Its GL type, e.g. `vec3`, `mat4`, `int`. */\n readonly type: string;\n /**\n * Named states for an integer selector, e.g. `u_colorSource`. The numbers\n * are append-only across releases (see the foundry's stability rules).\n */\n readonly namedValues?: Readonly<Record<string, number>>;\n}\n\n/** One fragment output. Its index in `outputs` is its location. */\nexport interface OutputSpec {\n readonly name: string;\n readonly type: string;\n /**\n * The attachment format the output requires, or `null` for no exact\n * requirement. `null` is a claim, not an omission.\n */\n readonly format: string | null;\n}\n\n/** A texture read at exact integer coordinates — a lookup table, not an image. */\nexport interface TableSpec {\n readonly name: string;\n readonly type: string;\n readonly format: string;\n readonly semantic: string;\n}\n\n/** An image sampled between texels. */\nexport interface TextureSpec {\n readonly name: string;\n readonly semantic: string;\n readonly kind: string;\n readonly component: string;\n readonly format: string;\n readonly requiresMipChain: boolean;\n /** The name of a sampler this contract declares. */\n readonly sampler: string;\n /** The semantic of a uv attribute this contract carries. */\n readonly uv: string;\n readonly selection: string;\n readonly neutral: readonly number[] | null;\n}\n\n/** Sampler state a texture is read through. */\nexport interface SamplerSpec {\n readonly name: string;\n readonly magFilter: string;\n readonly minFilter: string;\n readonly mipmapFilter: string;\n readonly wrapS: string;\n readonly wrapT: string;\n}\n\n/**\n * A pipeline's binding surface: everything a caller must match.\n *\n * Order is significant. A uniform block's member order determines its byte\n * offsets, which is why {@link RegistryEntry.contractSha256} is computed over\n * this document with its sequences left unsorted.\n */\nexport interface PipelineContract {\n readonly id: string;\n readonly capabilities: readonly string[];\n readonly inputs: readonly AttributeSpec[];\n readonly uniforms: readonly UniformSpec[];\n readonly outputs: readonly OutputSpec[];\n readonly tables: readonly TableSpec[];\n readonly textures: readonly TextureSpec[];\n readonly samplers: readonly SamplerSpec[];\n}\n\n/** Versions of the three executables that compiled a set. `null` where unread. */\nexport interface ToolchainInfo {\n readonly slangc: string | null;\n readonly spirvCross: string | null;\n readonly glslang: string | null;\n}\n\n/** What produced a set, and with what. */\nexport interface GeneratorInfo {\n readonly name: string;\n readonly version: string;\n readonly toolchain: ToolchainInfo | null;\n}\n\n/**\n * One index entry: enough to choose this pipeline, and where to go next.\n *\n * Not the contract. `contractSha256` names the envelope's content without\n * repeating it, so a fetched envelope can be checked against the entry that\n * pointed at it.\n */\nexport interface RegistryEntry {\n readonly id: string;\n readonly description: string;\n readonly capabilities: readonly string[];\n readonly contractSha256: string;\n /** The envelope's path within the set, relative and POSIX. */\n readonly envelope: string;\n}\n\n/** `registry.json`: the index a consumer selects from. */\nexport interface Registry {\n readonly schemaVersion: number;\n readonly generator: GeneratorInfo;\n /** The closed set of tags any pipeline in this set may declare. */\n readonly capabilityVocabulary: readonly string[];\n readonly pipelines: readonly RegistryEntry[];\n}\n\n/**\n * Where std140 placed one uniform block member.\n *\n * Read rather than recomputed: a second implementation of the padding rules is\n * a second thing to be wrong, and it would diverge silently — on one pipeline,\n * in one case, such as the sixteen-byte stride std140 gives the eight-byte\n * elements of a `vec2[72]`.\n */\nexport interface UniformLayout {\n /** Byte offset from the start of the block. */\n readonly offset: number;\n /** Total byte size, including any array padding. */\n readonly size: number;\n /**\n * Bytes between array elements. For a member that is not an array it is\n * what the reflection reports for its components: `4` for a vector, `0` for\n * a scalar or a matrix. The packer reads it only for an array.\n */\n readonly elementStride: number;\n /** The element type — `float`, `vec3`, `mat4`, `ivec2`. */\n readonly encoding: string | null;\n /** `row` or `column`, present only for a matrix. */\n readonly majorness?: \"row\" | \"column\";\n}\n\n/**\n * One emitted sampler uniform, and the resource it was built from.\n *\n * The seam the declared names do not cross: GLSL ES 3.00 has no binding\n * qualifier for samplers, so the cross-compiler pairs each texture with a\n * sampler and names the combination itself. A consumer binds by\n * {@link semantic}, then uses {@link uniform} and {@link unit}.\n */\nexport interface BindingRecord {\n /** The semantic of the table or texture this was built from. */\n readonly semantic: string;\n /** The declared name of that resource. It does not reach the program. */\n readonly texture: string;\n /**\n * The declared name of the sampler it was paired with, or `null` where the\n * contract declares none — a table read at exact texel coordinates is paired\n * with the cross-compiler's dummy sampler, which the contract never names.\n */\n readonly sampler: string | null;\n /** The uniform the emitted program actually declares. */\n readonly uniform: string;\n readonly component: string;\n readonly stage: ShaderStage;\n /** The texture unit to bind to, assigned deterministically at build. */\n readonly unit: number;\n}\n\n/** One stage's emitted source and its hash. */\nexport interface StageSource {\n readonly source: string;\n readonly sha256: string;\n}\n\n/** Everything about one pipeline in one language. */\nexport interface LanguageBlock {\n /**\n * The reflected size of the whole uniform block, which is larger than the\n * contract: the compiler emits its entire global block whatever entry point\n * is compiled, so an undeformed pipeline's GLSL still carries deform members\n * its contract does not list. Allocate this many bytes.\n */\n readonly blockSize: number;\n /** Placement of every member the block holds, by name. */\n readonly layout: Readonly<Record<string, UniformLayout>>;\n readonly bindings: readonly BindingRecord[];\n readonly stages: Readonly<Partial<Record<ShaderStage, StageSource>>>;\n}\n\n/**\n * One pipeline as a self-contained document: contract plus its shaders.\n *\n * The second projection of the manifest, for consumption rather than\n * selection. Fetching one is a single request that cannot arrive half-stale.\n */\nexport interface Envelope {\n readonly schemaVersion: number;\n readonly generator: GeneratorInfo;\n /** The contract, with the pipeline's description alongside it. */\n readonly pipeline: PipelineContract & { readonly description: string };\n readonly contractSha256: string;\n readonly languages: Readonly<Partial<Record<ShaderLanguage, LanguageBlock>>>;\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Reading an artifact set: where the documents come from, and what is checked.\n *\n * The set is two projections of one build. The index is fetched once, to list\n * what can be drawn; an envelope is fetched to draw one pipeline. {@link\n * ShaderSet} keeps that shape — the index eagerly, envelopes on demand and\n * cached — and makes the one check the split exists to enable: the envelope it\n * received carries the `contractSha256` the index entry that pointed at it\n * recorded.\n *\n * Where the bytes come from is a {@link ArtifactSource}, so the same set works\n * bundled, served over HTTP, or read from a directory on disk.\n */\n\nimport { layoutProblem } from \"./encoding.js\";\nimport type {\n Envelope,\n LanguageBlock,\n Registry,\n RegistryEntry,\n ShaderLanguage,\n} from \"./manifest.js\";\nimport { SCHEMA_VERSION } from \"./manifest.js\";\n\n/** Raised for any artifact set this package will not read. */\nexport class ShaderSetError extends Error {\n override readonly name = \"ShaderSetError\";\n}\n\n/**\n * Where an artifact set's documents come from.\n *\n * Two methods, because there are two documents. `readEnvelope` receives the\n * whole index entry rather than an id: the entry carries the envelope's path\n * within the set, which is the set's business and not the caller's to\n * reconstruct.\n */\nexport interface ArtifactSource {\n /** The parsed `registry.json`. */\n readRegistry(): Promise<unknown>;\n /** The parsed envelope the entry points at. */\n readEnvelope(entry: RegistryEntry): Promise<unknown>;\n}\n\n/**\n * What is wrong with a path inside the set, or `undefined` when nothing is.\n *\n * The rule the foundry's `check_relative_posix` and this repository's importer\n * apply: a plain relative POSIX path — no `..`, no `.`, no empty segment, no\n * leading slash, no backslash, no colon and no control character. Anything\n * else could name a file outside the set's directory, or, resolved against a\n * base URL, another path or another origin — which would also be sent the\n * caller's request headers. The colon refuses a scheme and a drive letter\n * alike, and the leading slash a protocol-relative `//host`.\n */\nfunction pathProblem(path: string): string | undefined {\n if (path.length === 0) return \"is empty\";\n // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what this refuses\n if (/[\\u0000-\\u001f\\u007f-\\u009f\\\\:]/.test(path)) {\n return \"holds a backslash, a colon or a control character\";\n }\n if (path.startsWith(\"/\")) return \"is absolute\";\n if (path.split(\"/\").some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n return 'has an empty, \".\" or \"..\" segment';\n }\n return undefined;\n}\n\n/** Refuse a path that could reach outside the set. */\nfunction assertPath(path: string, what: string): void {\n const problem = pathProblem(path);\n if (problem !== undefined) {\n throw new ShaderSetError(\n `${what} ${JSON.stringify(path)} ${problem}; a path inside the set is plain and relative.`,\n );\n }\n}\n\n/**\n * The base URL as an absolute URL.\n *\n * A relative base such as `/shaders/` is what a page naturally writes, and\n * `new URL` alone refuses it. In a browser it is resolved against the page's\n * own location, as a link would be; where there is no location there is\n * nothing to resolve it against, and guessing one would fetch from somewhere\n * the caller did not name.\n */\nfunction absoluteBase(baseUrl: string | URL): URL {\n if (baseUrl instanceof URL) return new URL(baseUrl.href);\n if (URL.canParse(baseUrl)) return new URL(baseUrl);\n const here = (globalThis as { location?: { href?: unknown } }).location?.href;\n if (typeof here === \"string\" && URL.canParse(baseUrl, here)) return new URL(baseUrl, here);\n throw new ShaderSetError(\n `${JSON.stringify(baseUrl)} is not an absolute URL, and there is no page location to ` +\n \"resolve it against. Outside a browser, pass an absolute URL such as \" +\n \"https://host/shaders/.\",\n );\n}\n\n/**\n * Reads a set served over HTTP under one base URL.\n *\n * A relative `baseUrl` is resolved against `location.href` where there is one\n * — in a browser — and refused elsewhere.\n *\n * @throws {ShaderSetError} for a relative `baseUrl` with no page location.\n */\nexport function fetchSource(baseUrl: string | URL, init?: RequestInit): ArtifactSource {\n const base = absoluteBase(baseUrl);\n // A base URL naming a directory must end in a slash or the last segment is\n // replaced rather than appended to.\n if (!base.pathname.endsWith(\"/\")) base.pathname += \"/\";\n\n const read = async (path: string): Promise<unknown> => {\n assertPath(path, \"the set path\");\n const url = new URL(path, base);\n // The rule above already keeps a path under the base; this states the\n // property it exists for, so the request and its headers go nowhere else.\n if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) {\n throw new ShaderSetError(`${url.href} is outside the set at ${base.href}.`);\n }\n const response = await fetch(url, init);\n if (!response.ok) {\n throw new ShaderSetError(\n `fetching ${url.href} failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n };\n\n return {\n readRegistry: () => read(\"registry.json\"),\n readEnvelope: (entry) => read(entry.envelope),\n };\n}\n\n/**\n * Reads a set unpacked into a directory on disk.\n *\n * `node:fs` is imported when the source is first read rather than when this\n * module is loaded, so importing this package in a browser does not pull a\n * Node built-in into the bundle.\n */\nexport function fsSource(directory: string): ArtifactSource {\n const read = async (path: string): Promise<unknown> => {\n const [{ readFile }, { join }] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:path\"),\n ]);\n assertPath(path, \"the set path\");\n const full = join(directory, ...path.split(\"/\"));\n try {\n return JSON.parse(await readFile(full, \"utf8\"));\n } catch (cause) {\n throw new ShaderSetError(`reading ${full} failed: ${(cause as Error).message}`, { cause });\n }\n };\n\n return {\n readRegistry: () => read(\"registry.json\"),\n readEnvelope: (entry) => read(entry.envelope),\n };\n}\n\nfunction assertSchema(document: { schemaVersion?: unknown }, what: string): void {\n if (document.schemaVersion !== SCHEMA_VERSION) {\n throw new ShaderSetError(\n `${what} is schema version ${String(document.schemaVersion)}, and this package reads ` +\n `${SCHEMA_VERSION}. A document whose shape is not the one expected is refused rather ` +\n \"than read with its fields misinterpreted.\",\n );\n }\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Check a capability list is an array of distinct strings.\n *\n * A repeated tag is not harmless: the exact match compares sizes, and a list\n * of `a, a` has the length of `{a, b}`.\n */\nfunction assertTags(tags: unknown, what: string): void {\n if (!Array.isArray(tags) || !tags.every((tag) => typeof tag === \"string\")) {\n throw new ShaderSetError(`${what} is not an array of capability tags.`);\n }\n const repeated = tags.filter((tag, index) => tags.indexOf(tag) !== index);\n if (repeated.length > 0) {\n throw new ShaderSetError(`${what} repeats the tag(s) ${[...new Set(repeated)].join(\", \")}.`);\n }\n}\n\nfunction assertEntry(entry: unknown, index: number): void {\n if (!isObject(entry) || typeof entry.id !== \"string\") {\n throw new ShaderSetError(`registry.json pipeline ${index} has no id.`);\n }\n for (const field of [\"contractSha256\", \"envelope\"] as const) {\n if (typeof entry[field] !== \"string\") {\n throw new ShaderSetError(`registry.json entry ${entry.id} has no ${field}.`);\n }\n }\n assertPath(entry.envelope as string, `registry.json entry ${entry.id} has the envelope path`);\n assertTags(entry.capabilities, `the capabilities of registry.json entry ${entry.id}`);\n}\n\nfunction asRegistry(document: unknown): Registry {\n if (!isObject(document)) {\n throw new ShaderSetError(\"registry.json is not an object.\");\n }\n assertSchema(document, \"registry.json\");\n if (!Array.isArray(document.pipelines)) {\n throw new ShaderSetError(\"registry.json carries no pipelines array.\");\n }\n assertTags(document.capabilityVocabulary, \"the capabilityVocabulary of registry.json\");\n document.pipelines.forEach(assertEntry);\n // A tag outside the vocabulary could never be asked for by name, only\n // matched by accident, and says the index was not built as one piece.\n const vocabulary = new Set(document.capabilityVocabulary as string[]);\n for (const entry of document.pipelines as RegistryEntry[]) {\n const unknown = entry.capabilities.filter((tag) => !vocabulary.has(tag));\n if (unknown.length > 0) {\n throw new ShaderSetError(\n `registry.json entry ${entry.id} carries ${unknown.join(\", \")}, which ` +\n \"capabilityVocabulary does not declare.\",\n );\n }\n }\n const ids = (document.pipelines as RegistryEntry[]).map((entry) => entry.id);\n const repeated = ids.filter((id, index) => ids.indexOf(id) !== index);\n if (repeated.length > 0) {\n throw new ShaderSetError(`registry.json lists ${repeated.join(\", \")} more than once.`);\n }\n return document as unknown as Registry;\n}\n\n/**\n * Check one language block is something the packer and binder can use.\n *\n * The layout is checked against itself, not recomputed: each member must sit\n * at a four-byte-aligned offset, its recorded extent must lie inside the\n * recorded block size, and its encoding must be one the packer writes.\n */\nfunction assertLanguage(id: string, language: string, block: unknown): void {\n const where = `the ${language} block of the envelope for ${id}`;\n if (!isObject(block)) throw new ShaderSetError(`${where} is not an object.`);\n const { blockSize, layout, bindings, stages } = block;\n if (typeof blockSize !== \"number\" || !Number.isInteger(blockSize) || blockSize <= 0) {\n throw new ShaderSetError(`${where} reports a block size of ${String(blockSize)}.`);\n }\n if (!isObject(layout)) throw new ShaderSetError(`${where} carries no layout.`);\n for (const [name, member] of Object.entries(layout)) {\n const problem = layoutProblem(name, member as never, blockSize);\n if (problem !== undefined) throw new ShaderSetError(`in ${where}, ${problem}`);\n }\n if (!Array.isArray(bindings)) throw new ShaderSetError(`${where} carries no bindings.`);\n if (!isObject(stages)) throw new ShaderSetError(`${where} carries no stages.`);\n}\n\nfunction asEnvelope(document: unknown, entry: RegistryEntry): Envelope {\n if (typeof document !== \"object\" || document === null) {\n throw new ShaderSetError(`the envelope for ${entry.id} is not an object.`);\n }\n const envelope = document as Envelope;\n assertSchema(envelope, `the envelope for ${entry.id}`);\n if (envelope.pipeline?.id !== entry.id) {\n throw new ShaderSetError(\n `${entry.envelope} describes pipeline ${String(envelope.pipeline?.id)}, but the index ` +\n `points at it for ${entry.id}.`,\n );\n }\n // The whole reason the index carries a hash instead of the contract: an\n // envelope that is not the one the index sent us to would bind at the wrong\n // offsets and draw a wrong picture with no error anywhere.\n if (envelope.contractSha256 !== entry.contractSha256) {\n throw new ShaderSetError(\n `the envelope for ${entry.id} carries contract ${envelope.contractSha256}, but the index ` +\n `entry that pointed at it records ${entry.contractSha256}. The set is mixed: the index ` +\n \"and this envelope are from different builds.\",\n );\n }\n assertTags(envelope.pipeline.capabilities, `the capabilities in the envelope for ${entry.id}`);\n // The pipeline was chosen by the index entry's capabilities; the contract\n // handed to the renderer must be for that same set. The carried hash is\n // compared as a string, not recomputed, so it does not show this.\n const selected = new Set(entry.capabilities);\n const carried = new Set(envelope.pipeline.capabilities);\n if (selected.size !== carried.size || [...carried].some((tag) => !selected.has(tag))) {\n throw new ShaderSetError(\n `the envelope for ${entry.id} declares the capabilities ` +\n `[${[...carried].sort().join(\", \")}], but the index entry that selected it records ` +\n `[${[...selected].sort().join(\", \")}].`,\n );\n }\n if (!isObject(envelope.languages)) {\n throw new ShaderSetError(`the envelope for ${entry.id} carries no languages.`);\n }\n for (const [language, block] of Object.entries(envelope.languages)) {\n assertLanguage(entry.id, language, block);\n }\n return envelope;\n}\n\n/**\n * One artifact set, opened.\n *\n * Holds the index and caches each envelope it has been asked for. Every\n * envelope it hands out has been checked against the entry that pointed at it.\n */\nexport class ShaderSet {\n readonly #source: ArtifactSource;\n readonly #entries: ReadonlyMap<string, RegistryEntry>;\n readonly #envelopes = new Map<string, Promise<Envelope>>();\n\n /** The index, as read. */\n readonly registry: Registry;\n\n private constructor(source: ArtifactSource, registry: Registry) {\n this.#source = source;\n this.registry = registry;\n this.#entries = new Map(registry.pipelines.map((entry) => [entry.id, entry]));\n }\n\n /** Read the index and open the set. */\n static async open(source: ArtifactSource): Promise<ShaderSet> {\n return new ShaderSet(source, asRegistry(await source.readRegistry()));\n }\n\n /** Every pipeline the set holds, in the order the index lists them. */\n get pipelines(): readonly RegistryEntry[] {\n return this.registry.pipelines;\n }\n\n /** The closed set of capability tags any pipeline here may declare. */\n get capabilityVocabulary(): readonly string[] {\n return this.registry.capabilityVocabulary;\n }\n\n /** The index entry for `id`. */\n entry(id: string): RegistryEntry {\n const entry = this.#entries.get(id);\n if (entry === undefined) {\n throw new ShaderSetError(`no pipeline ${id} in this set; it holds ${this.#entries.size}.`);\n }\n return entry;\n }\n\n /** The envelope for `id`, fetched once and cached. */\n async envelope(id: string): Promise<Envelope> {\n const entry = this.entry(id);\n let pending = this.#envelopes.get(id);\n if (pending === undefined) {\n pending = this.#source.readEnvelope(entry).then((document) => asEnvelope(document, entry));\n // A failed read must not be cached, or one network blip poisons the id\n // for the lifetime of the set.\n pending.catch(() => this.#envelopes.delete(id));\n this.#envelopes.set(id, pending);\n }\n return pending;\n }\n\n /** The envelope's block for one language; `glsl` unless asked otherwise. */\n static language(envelope: Envelope, language: ShaderLanguage = \"glsl\"): LanguageBlock {\n const block = Object.hasOwn(envelope.languages, language)\n ? envelope.languages[language]\n : undefined;\n if (block === undefined) {\n const carried = Object.keys(envelope.languages).join(\", \") || \"none\";\n throw new ShaderSetError(\n `the envelope for ${envelope.pipeline.id} carries no ${language}; it carries ${carried}.`,\n );\n }\n return block;\n }\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Writing the uniform block, at the offsets the build reported.\n *\n * Nothing here computes std140. The envelope carries the reflected placement\n * of every member and the size of the whole block, and this writes into that;\n * a second implementation of the padding rules would be a second thing to be\n * wrong and would diverge silently — on one pipeline, in one case, such as the\n * sixteen-byte stride std140 gives the four-byte elements of an `int[72]`.\n *\n * The block is larger than the contract. The compiler emits its entire global\n * uniform block whatever entry point was compiled, so an undeformed pipeline's\n * GLSL still declares the deform members its contract does not list. Allocate\n * {@link LanguageBlock.blockSize}; write what you have; leave the rest zero.\n */\n\nimport type { Kind } from \"./encoding.js\";\nimport { describeEncoding, layoutProblem } from \"./encoding.js\";\nimport type { LanguageBlock, UniformLayout } from \"./manifest.js\";\n\n/** Raised for a write this packer will not make. */\nexport class UniformPackError extends Error {\n override readonly name = \"UniformPackError\";\n}\n\n/** How a matrix's elements are ordered in memory. */\nexport type Majorness = \"row\" | \"column\";\n\nconst INT32_MIN = -(2 ** 31);\nconst INT32_MAX = 2 ** 31 - 1;\nconst UINT32_MAX = 2 ** 32 - 1;\n\n/** Why `value` cannot be stored as `kind`, or `undefined` if it can. */\nfunction scalarProblem(kind: Kind, value: number): string | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return \"not a finite number\";\n if (kind === \"float\") return undefined;\n if (!Number.isInteger(value)) return `not an integer, and the member is ${kind}`;\n if (kind === \"int\" && (value < INT32_MIN || value > INT32_MAX)) {\n return \"outside the 32-bit signed range\";\n }\n if (kind === \"uint\" && (value < 0 || value > UINT32_MAX)) {\n return \"outside the 32-bit unsigned range\";\n }\n return undefined;\n}\n\n/**\n * One pipeline's uniform block, allocated and writable by member name.\n *\n * Create one per draw target and reuse it: the buffer is the thing uploaded,\n * and rewriting a member in place is cheaper than rebuilding it. Members never\n * written stay zero, which is the off state every always-present feature\n * defines for itself — a plane count of zero, a scale of zero.\n *\n * ## Matrices, and why the transpose goes the other way\n *\n * Hand {@link UniformBlock.set} a conventional column-major matrix and the\n * shaders apply that matrix. Getting there takes two corrections that happen\n * to cancel, and only one of them is visible in the layout:\n *\n * 1. The block declares its matrices `row_major`, so each sixteen-byte slot\n * holds a **row** of the GLSL variable rather than a column.\n * 2. The features are authored in Slang, which multiplies the HLSL way round,\n * and the emitted GLSL keeps it — `position * u_mvpMatrix`, never\n * `u_mvpMatrix * position`. In GLSL `v * M` is `transpose(M) * v`, so the\n * transform a shader applies is the transpose of the matrix it is given.\n *\n * Reading the layout and ignoring the multiply order gives a transposed\n * camera. That is a rotation's inverse, so it survives casual inspection: an\n * identity is unchanged by it, and so are the front, back, top and bottom\n * views of a symmetric model. It shows up as left and right views that are\n * mirrored, and as translations that travel along the wrong axis.\n *\n * So a column-major input is written through **untransposed** into a\n * `row_major` block, and transposed into a `column_major` one — the opposite\n * of what point 1 alone would ask for. `majorness` still describes the input\n * array's own order and nothing else; it is not a way to ask for a transpose.\n */\nexport class UniformBlock {\n readonly #layout: Readonly<Record<string, UniformLayout>>;\n readonly #floats: Float32Array;\n readonly #ints: Int32Array;\n readonly #uints: Uint32Array;\n\n /** The bytes to upload. */\n readonly buffer: ArrayBuffer;\n\n constructor(block: LanguageBlock) {\n if (!Number.isInteger(block.blockSize) || block.blockSize <= 0) {\n throw new UniformPackError(\n `the envelope reports a block size of ${String(block.blockSize)}.`,\n );\n }\n // Every member is checked now, not when it is first written: a layout the\n // packer cannot honour is a property of the envelope, and an encoding it\n // does not know would otherwise be written as if it were one float.\n for (const [name, layout] of Object.entries(block.layout)) {\n const problem = layoutProblem(name, layout, block.blockSize);\n if (problem !== undefined) throw new UniformPackError(problem);\n }\n this.#layout = block.layout;\n this.buffer = new ArrayBuffer(block.blockSize);\n // Every member in the block is four-byte aligned, so three views over the\n // one buffer cover every encoding without a DataView's per-write cost.\n this.#floats = new Float32Array(this.buffer);\n this.#ints = new Int32Array(this.buffer);\n this.#uints = new Uint32Array(this.buffer);\n }\n\n /** The block's size in bytes. */\n get byteLength(): number {\n return this.buffer.byteLength;\n }\n\n /** Whether the block declares `name`. */\n has(name: string): boolean {\n return Object.hasOwn(this.#layout, name) && this.#layout[name]?.encoding != null;\n }\n\n /** Every member the block declares. */\n get members(): readonly string[] {\n return Object.keys(this.#layout);\n }\n\n /** Zero the whole block. */\n clear(): this {\n this.#floats.fill(0);\n return this;\n }\n\n #entry(name: string): { layout: UniformLayout; encoding: string } {\n const layout = Object.hasOwn(this.#layout, name) ? this.#layout[name] : undefined;\n if (layout === undefined) {\n throw new UniformPackError(\n `the uniform block declares no ${name}. It declares ${this.members.length} member(s); ` +\n \"a name absent here is either a typo or a uniform this pipeline does not carry.\",\n );\n }\n if (layout.encoding == null) {\n throw new UniformPackError(\n `${name} has no encoding the build could report, so its bytes would be a guess. It is ` +\n \"part of the block and counts towards its size, but it cannot be written.\",\n );\n }\n return { layout, encoding: layout.encoding };\n }\n\n #writeScalars(\n kind: Kind,\n at: number,\n values: ArrayLike<number>,\n count: number,\n name: string,\n ): void {\n for (let index = 0; index < count; index++) {\n const value = values[index] as number;\n const problem = scalarProblem(kind, value);\n if (problem !== undefined) {\n throw new UniformPackError(`${name}[${index}] is ${String(value)}, which is ${problem}.`);\n }\n const slot = at + index;\n if (kind === \"float\") this.#floats[slot] = value;\n else if (kind === \"int\") this.#ints[slot] = value;\n else this.#uints[slot] = value;\n }\n }\n\n /**\n * Write one member.\n *\n * Accepts what the member's shape needs: a number for a scalar, a flat array\n * of components for a vector or matrix, and either a flat array or an array\n * of elements for an array member.\n *\n * A matrix is taken as column-major — the order GL APIs and every mat4\n * library produce — and is written so that the emitted shaders apply *that*\n * transform. See {@link UniformBlock} on why the bytes that achieve it are\n * not the ones the block's `row_major` qualifier alone would suggest. Pass\n * `majorness: \"row\"` only when the input array is itself row-major.\n */\n set(\n name: string,\n value: number | boolean | ArrayLike<number> | ReadonlyArray<ArrayLike<number>>,\n options?: { majorness?: Majorness },\n ): this {\n const { layout, encoding } = this.#entry(name);\n // Checked when the block was built, so the encoding is known.\n const { kind, width, order, isArray } = describeEncoding(encoding) as NonNullable<\n ReturnType<typeof describeEncoding>\n >;\n\n if (typeof value === \"boolean\") value = value ? 1 : 0;\n\n if (typeof value === \"number\") {\n if (isArray || width !== 1) {\n throw new UniformPackError(`${name} is ${encoding}; a single number cannot fill it.`);\n }\n this.#writeScalars(kind, layout.offset / 4, [value], 1, name);\n return this;\n }\n\n // An array of arrays is flattened to its components; anything else is\n // already flat. Doing this once keeps the width checks below in one place.\n const flat: number[] | ArrayLike<number> =\n value.length > 0 && typeof (value as ReadonlyArray<ArrayLike<number>>)[0] === \"object\"\n ? (value as ReadonlyArray<ArrayLike<number>>).flatMap((item) => Array.from(item))\n : (value as ArrayLike<number>);\n\n if (order !== undefined) {\n if (isArray)\n throw new UniformPackError(`${name} is an array of matrices, which is not supported.`);\n this.#setMatrix(name, layout, order, flat, options?.majorness ?? \"column\");\n return this;\n }\n\n if (!isArray) {\n if (flat.length !== width) {\n throw new UniformPackError(\n `${name} is ${encoding} and needs ${width} component(s); got ${flat.length}.`,\n );\n }\n this.#writeScalars(kind, layout.offset / 4, flat, width, name);\n return this;\n }\n\n // An array member's elements sit at elementStride bytes apart, which for a\n // vec2[] or an int[] is padding, not packing: std140 rounds every array\n // element up to sixteen bytes.\n // The stride was checked when the block was built: a positive multiple of\n // four that holds one element.\n const stride = layout.elementStride;\n const capacity = Math.floor(layout.size / stride);\n if (flat.length % width !== 0) {\n throw new UniformPackError(\n `${name} is ${encoding}; ${flat.length} value(s) is not a whole number of ${width}-component elements.`,\n );\n }\n const count = flat.length / width;\n if (count > capacity) {\n throw new UniformPackError(`${name} holds ${capacity} element(s); got ${count}.`);\n }\n for (let index = 0; index < count; index++) {\n const at = (layout.offset + index * stride) / 4;\n this.#writeScalars(\n kind,\n at,\n Array.prototype.slice.call(flat, index * width, (index + 1) * width),\n width,\n name,\n );\n }\n return this;\n }\n\n #setMatrix(\n name: string,\n layout: UniformLayout,\n order: number,\n values: ArrayLike<number>,\n given: Majorness,\n ): void {\n if (values.length !== order * order) {\n throw new UniformPackError(\n `${name} is mat${order} and needs ${order * order} values; got ${values.length}.`,\n );\n }\n // Whatever its majorness, a matrix is stored as `order` rows or columns of\n // sixteen bytes each — std140 gives every one of them a vec4's alignment.\n const wanted = layout.majorness ?? \"column\";\n const base = layout.offset / 4;\n for (let major = 0; major < order; major++) {\n for (let minor = 0; minor < order; minor++) {\n // Reading index (minor, major) from the input in its own order, and\n // writing it to slot `major` of the block's order.\n //\n // Transposing when the two orders *agree* looks backwards and is the\n // whole point: the shaders multiply row-vector-first, so the matrix\n // they apply is already the transpose of the one they are handed, and\n // the storage order has to undo that rather than compound it. The\n // class comment works it through.\n const source = wanted === given ? minor * order + major : major * order + minor;\n const value = values[source] as number;\n if (scalarProblem(\"float\", value) !== undefined) {\n throw new UniformPackError(\n `${name}[${source}] is ${String(value)}, which is not a finite number.`,\n );\n }\n this.#floats[base + major * 4 + minor] = value;\n }\n }\n }\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Choosing a pipeline.\n *\n * A pipeline's id names its vertex variant and its fragment shape; its\n * capability set is what a consumer matches on. The match is **exact**: a\n * capability set is a description of what the pipeline does, not a list of\n * minimum requirements, and a pipeline carrying a capability you did not ask\n * for will read an attribute you did not bind.\n *\n * Nothing here ranks. The artifact set carries no defaults, no preference\n * order and no fallbacks, and inventing one in this package would make it a\n * policy every consumer inherits without asking. What is here is the exact\n * match, and the filters a caller needs to build its own choice.\n */\n\nimport type { Registry, RegistryEntry } from \"./manifest.js\";\n\n/** Raised when a request cannot be resolved to one pipeline. */\nexport class PipelineSelectionError extends Error {\n override readonly name = \"PipelineSelectionError\";\n}\n\nconst asSet = (tags: Iterable<string>): ReadonlySet<string> => new Set(tags);\n\nfunction sameSet(a: ReadonlySet<string>, b: readonly string[]): boolean {\n // Compared as sets on both sides: a list that repeats a tag must not pass\n // for a larger set on length alone. A loaded set refuses repeats anyway;\n // this keeps the match exact for entries built by hand.\n const other = asSet(b);\n if (a.size !== other.size) return false;\n for (const tag of other) if (!a.has(tag)) return false;\n return true;\n}\n\n/**\n * Check every tag against the set's own vocabulary.\n *\n * The vocabulary is closed per document, so a tag outside it can never match\n * anything. Catching that here names the typo; leaving it to\n * {@link matchCapabilities} would report only that nothing matched.\n */\nexport function validateCapabilities(registry: Registry, capabilities: Iterable<string>): void {\n const vocabulary = new Set(registry.capabilityVocabulary);\n const unknown = [...asSet(capabilities)].filter((tag) => !vocabulary.has(tag));\n if (unknown.length > 0) {\n throw new PipelineSelectionError(\n `capability tag(s) not in this set's vocabulary: ${unknown.join(\", \")}. The vocabulary is ` +\n `closed, so no pipeline here can carry them. It holds: ${registry.capabilityVocabulary.join(\", \")}.`,\n );\n }\n}\n\n/** Every pipeline whose capability set is exactly `capabilities`. */\nexport function matchCapabilities(\n entries: readonly RegistryEntry[],\n capabilities: Iterable<string>,\n): RegistryEntry[] {\n const wanted = asSet(capabilities);\n return entries.filter((entry) => sameSet(wanted, entry.capabilities));\n}\n\n/**\n * The one pipeline whose capability set is exactly `capabilities`.\n *\n * @throws {PipelineSelectionError} if none matches, or more than one does —\n * an ambiguous match is a set whose matrix has two pipelines with the same\n * capabilities, which is a question for the builder, not something to\n * resolve by picking the first.\n */\nexport function resolvePipeline(\n registry: Registry,\n capabilities: Iterable<string>,\n): RegistryEntry {\n validateCapabilities(registry, capabilities);\n const wanted = [...asSet(capabilities)].sort();\n const matches = matchCapabilities(registry.pipelines, wanted);\n if (matches.length === 1) return matches[0] as RegistryEntry;\n if (matches.length === 0) {\n throw new PipelineSelectionError(\n `no pipeline in this set has exactly the capabilities {${wanted.join(\", \")}}. The match is ` +\n \"exact: a pipeline carrying a capability you did not ask for reads an attribute you did \" +\n \"not bind.\",\n );\n }\n throw new PipelineSelectionError(\n `${matches.length} pipelines share the capabilities {${wanted.join(\", \")}}: ` +\n `${matches.map((entry) => entry.id).join(\", \")}.`,\n );\n}\n\n/** Every pipeline carrying all of `capabilities`, whatever else it carries. */\nexport function withCapabilities(\n entries: readonly RegistryEntry[],\n capabilities: Iterable<string>,\n): RegistryEntry[] {\n const wanted = [...asSet(capabilities)];\n return entries.filter((entry) => wanted.every((tag) => entry.capabilities.includes(tag)));\n}\n\n/**\n * Every tag any of `entries` declares, sorted.\n *\n * For building a chooser: the vocabulary is what the features offer, this is\n * what this set actually reaches.\n */\nexport function capabilitiesInUse(entries: readonly RegistryEntry[]): string[] {\n return [...new Set(entries.flatMap((entry) => [...entry.capabilities]))].sort();\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n/**\n * Reading back a pick texel.\n *\n * The pick pass writes per-pixel identifiers into an integer attachment\n * instead of a color. Four unsigned 32-bit channels: the primitive id, the\n * view depth, the group id and one reserved. Decoding them is arithmetic, not\n * GPU work, so\n * it lives here rather than in a renderer — a WebGPU consumer reads the same\n * texel and must read it the same way.\n *\n * **Three things about the layout are easy to get wrong, and two fail\n * silently**, which is why this is written once:\n *\n * - The depth channel holds the *bits* of a `float32`, not a number. Read as\n * an integer it is a value in the billions.\n * - A pixel where nothing was drawn carries {@link PICK_EMPTY} in every\n * channel, and emptiness must be tested on the identifier alone. The group\n * id's channel is not a substitute: a hit can carry any value there, the\n * sentinel's bits included.\n * - The target must be cleared to {@link PICK_EMPTY} before the pass. Cleared\n * to zero, every empty pixel decodes as primitive 0.\n *\n * The layout is the `pick` feature's, mirrored from its Python.\n */\n\nimport type { Registry, RegistryEntry } from \"./manifest.js\";\nimport { PipelineSelectionError, withCapabilities } from \"./select.js\";\n\n/** The capability tag a pick pipeline declares. */\nexport const PICK_CAPABILITY = \"pick\";\n\n/**\n * The value every channel carries where no geometry was drawn, and what the\n * target is cleared to before the pass.\n */\nexport const PICK_EMPTY = 0xffffffff;\n\n/** What a fragment writes into the reserved channel. */\nexport const PICK_RESERVED = 0;\n\n/** What each channel of the texel holds, in order. */\nexport const PICK_CHANNELS = [\"primitiveId\", \"depth\", \"groupId\", \"reserved\"] as const;\n\n/**\n * The capability tags that change where the vertex stage puts geometry. A pick\n * pipeline must carry each one its color pipeline carries: these are not\n * optional extras a smaller pick pipeline may leave out.\n */\nconst DEFORM_CAPABILITIES = [\"deform3\", \"deform6\"] as const;\n\n/** What one pick texel identifies. */\nexport interface Pick {\n /** The primitive id the fragment carried, as the caller's data set it. */\n readonly primitiveId: number;\n /**\n * Distance along the camera's forward axis — `-z` in view space, not a\n * normalized depth. The caller owns the ray, so a depth is enough to place\n * the point and costs one channel where a position would cost three.\n */\n readonly depth: number;\n /**\n * The scene atom: `a_atomId + u_maskLutBase`, the row of the scene mask the\n * fragment was drawn by. When each occurrence of a mesh is drawn with its own\n * block of the scene mask, this names the occurrence and the atom in one\n * number; two draws of one vertex buffer share their primitive ids, so it is\n * what tells a click on one from the other. With the base at zero it is the\n * mesh's own atom id, and occurrences cannot be told apart.\n */\n readonly groupId: number;\n}\n\n/** Raised for a texel that cannot have come from a pick pass. */\nexport class PickDecodeError extends Error {\n override readonly name = \"PickDecodeError\";\n}\n\n// One buffer, reused: the depth channel is a reinterpretation, so the bits go\n// in as an unsigned integer and come out as the float they always were.\nconst scratch = new ArrayBuffer(4);\nconst asUint = new Uint32Array(scratch);\nconst asFloat = new Float32Array(scratch);\n\n/**\n * Decode one texel of a pick readback, or `null` where nothing was drawn.\n *\n * @param texel the four channel values, as unsigned 32-bit integers — four\n * elements of the `Uint32Array` a `readPixels` of an `rgba32ui` attachment\n * fills, at the offset of the pixel wanted.\n * @throws {PickDecodeError} if a channel does not fit in 32 bits, which means\n * the readback was decoded at the wrong width and every field is suspect.\n */\nexport function decodePick(texel: ArrayLike<number>, offset = 0): Pick | null {\n if (texel.length - offset < 4) {\n throw new PickDecodeError(\n `a pick texel is 4 channels; ${texel.length - offset} are available from offset ${offset}.`,\n );\n }\n for (let channel = 0; channel < 4; channel++) {\n const value = texel[offset + channel] as number;\n if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {\n throw new PickDecodeError(\n `the ${PICK_CHANNELS[channel]} channel is ${String(value)}, which is not a 32-bit unsigned ` +\n \"integer. The readback was decoded at the wrong width, so every field is suspect.\",\n );\n }\n }\n\n const primitiveId = texel[offset] as number;\n // Tested on the identifier, never on another channel.\n if (primitiveId === PICK_EMPTY) return null;\n\n asUint[0] = texel[offset + 1] as number;\n return { primitiveId, depth: asFloat[0] as number, groupId: texel[offset + 2] as number };\n}\n\n/**\n * The pick pipeline that matches a color pipeline.\n *\n * Picking is a second draw of the same geometry, so the two passes must agree\n * on everything the vertex stage does — above all the deform variant, or\n * deformed geometry is picked where it is not drawn.\n *\n * Found by capability: a pick pipeline is compatible when it asks for nothing\n * the color pass does not already have, and carries the color pipeline's\n * deform variant (`deform3` or `deform6`) — the one difference that would put\n * picked geometry somewhere other than where it is drawn, so it is required\n * rather than preferred. Of the compatible ones, the one carrying the most\n * capabilities keeps the most of the vertex stage in step.\n *\n * @throws {PipelineSelectionError} if the set has no compatible pick pipeline\n * — including when it has pick pipelines, but none with the color\n * pipeline's deform variant — or two equally good ones.\n */\nexport function pickPipelineFor(registry: Registry, color: RegistryEntry): RegistryEntry {\n const available = new Set<string>([...color.capabilities, PICK_CAPABILITY]);\n const deform = DEFORM_CAPABILITIES.filter((tag) => available.has(tag));\n const compatible = withCapabilities(registry.pipelines, [PICK_CAPABILITY, ...deform]).filter(\n (entry) => entry.capabilities.every((tag) => available.has(tag)),\n );\n if (compatible.length === 0) {\n const variant = deform.length > 0 ? ` carrying ${deform.join(\", \")}` : \"\";\n throw new PipelineSelectionError(\n `this set has no pick pipeline${variant} compatible with ${color.id}. Picking draws the ` +\n \"same geometry a second time, so it needs a pick pipeline whose vertex stage matches.\",\n );\n }\n const best = Math.max(...compatible.map((entry) => entry.capabilities.length));\n const winners = compatible.filter((entry) => entry.capabilities.length === best);\n if (winners.length > 1) {\n throw new PipelineSelectionError(\n `${color.id} has ${winners.length} equally compatible pick pipelines: ` +\n `${winners.map((entry) => entry.id).join(\", \")}.`,\n );\n }\n return winners[0] as RegistryEntry;\n}\n","// Copyright Visual Collaboration Technologies Inc. All Rights Reserved.\n// See LICENSE for details.\n\n// __PKG_VERSION__ is replaced with the package.json version at build time by\n// tsup (see tsup.config.ts) and by vitest during tests (see vitest.config.ts).\n// package.json remains the single source of truth; it stays out of the TS\n// program so tsc can emit declarations cleanly (see tsconfig.build.json).\ndeclare const __PKG_VERSION__: string;\n\n/** The package version, injected from package.json at build time. */\nexport const VERSION: string = __PKG_VERSION__;\n"]}