typegpu 0.9.0 → 0.10.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.
Files changed (48) hide show
  1. package/README.md +1 -1
  2. package/builtin-ClEnM-Ye.js +818 -0
  3. package/builtin-ClEnM-Ye.js.map +1 -0
  4. package/chunk-BYypO7fO.js +18 -0
  5. package/common/index.d.ts +8 -23
  6. package/common/index.d.ts.map +1 -0
  7. package/common/index.js +7 -5
  8. package/common/index.js.map +1 -1
  9. package/data/index.d.ts +7 -401
  10. package/data/index.d.ts.map +1 -0
  11. package/data/index.js +164 -1
  12. package/data/index.js.map +1 -1
  13. package/deepEqual-yZXvaV2C.js +413 -0
  14. package/deepEqual-yZXvaV2C.js.map +1 -0
  15. package/extensions-0SFbU9FH.js +2032 -0
  16. package/extensions-0SFbU9FH.js.map +1 -0
  17. package/fullScreenTriangle-MdLGaAMR.js +543 -0
  18. package/fullScreenTriangle-MdLGaAMR.js.map +1 -0
  19. package/index.d.ts +124 -310
  20. package/index.d.ts.map +1 -0
  21. package/index.js +6282 -153
  22. package/index.js.map +1 -1
  23. package/indexNamedExports-Cdy7USiY.d.ts +5696 -0
  24. package/indexNamedExports-Cdy7USiY.d.ts.map +1 -0
  25. package/operators-HTxa_0k9.js +4156 -0
  26. package/operators-HTxa_0k9.js.map +1 -0
  27. package/package.json +3 -2
  28. package/std/index.d.ts +7 -621
  29. package/std/index.d.ts.map +1 -0
  30. package/std/index.js +165 -1
  31. package/std/index.js.map +1 -1
  32. package/texture-Dg5ybJro.js +205 -0
  33. package/texture-Dg5ybJro.js.map +1 -0
  34. package/chunk-5ABKYSJD.js +0 -2
  35. package/chunk-5ABKYSJD.js.map +0 -1
  36. package/chunk-D5UYO3OX.js +0 -3
  37. package/chunk-D5UYO3OX.js.map +0 -1
  38. package/chunk-EHLRP4V2.js +0 -2
  39. package/chunk-EHLRP4V2.js.map +0 -1
  40. package/chunk-LMPPDGRD.js +0 -2
  41. package/chunk-LMPPDGRD.js.map +0 -1
  42. package/chunk-MBB2XFH6.js +0 -2
  43. package/chunk-MBB2XFH6.js.map +0 -1
  44. package/chunk-SHSILTWI.js +0 -10
  45. package/chunk-SHSILTWI.js.map +0 -1
  46. package/comptime-DKpw1IVu.d.ts +0 -28
  47. package/matrix-C4IFKU1R.d.ts +0 -123
  48. package/tgpuConstant-BOn7U_lv.d.ts +0 -4031
@@ -0,0 +1,543 @@
1
+ import { $n as getMetaData, At as stitch, Bn as isNaturallyEphemeral, Cn as isDisarray, Dn as undecorate, Jn as isWgslData, Kt as isWgsl, Mt as getResolutionCtx, O as coerceToSnippet, Un as isVec, Vn as isPtr, Vt as getOwnSnippet, W as vec3f, Wt as isKnownAtComptime, Y as vec4f, Yn as isWgslStruct, _n as MatrixColumnsAccess, ar as $getNameForward, bt as derefSnippet, cr as $internal, dn as isEphemeralSnippet, er as getName, fr as $resolve, kn as Void, lr as $ownSnippet, mn as snip, nn as MissingLinksError, nr as isNamable, qn as isWgslArray, rr as setName, sr as $gpuValueOf, tr as hasTinyestMetadata, vn as UnknownData, wn as isLooseData, z as vec2f } from "./operators-HTxa_0k9.js";
2
+ import { c as getAttributesString, o as createIoSchema, r as accessProp, t as builtin } from "./builtin-ClEnM-Ye.js";
3
+
4
+ //#region src/getGPUValue.ts
5
+ function getGPUValue(object) {
6
+ return object?.[$gpuValueOf];
7
+ }
8
+
9
+ //#endregion
10
+ //#region src/tgsl/accessIndex.ts
11
+ const indexableTypeToResult = {
12
+ mat2x2f: vec2f,
13
+ mat3x3f: vec3f,
14
+ mat4x4f: vec4f
15
+ };
16
+ function accessIndex(target, indexArg) {
17
+ const index = typeof indexArg === "number" ? coerceToSnippet(indexArg) : indexArg;
18
+ if (isWgslArray(target.dataType) || isDisarray(target.dataType)) {
19
+ const elementType = target.dataType.elementType;
20
+ const isElementNatEph = isNaturallyEphemeral(elementType);
21
+ const isTargetEphemeral = isEphemeralSnippet(target);
22
+ const isIndexConstant = index.origin === "constant";
23
+ let origin;
24
+ if (target.origin === "constant-tgpu-const-ref") if (isIndexConstant) origin = isElementNatEph ? "constant" : "constant-tgpu-const-ref";
25
+ else origin = isElementNatEph ? "runtime" : "runtime-tgpu-const-ref";
26
+ else if (target.origin === "runtime-tgpu-const-ref") origin = isElementNatEph ? "runtime" : "runtime-tgpu-const-ref";
27
+ else if (!isTargetEphemeral && !isElementNatEph) origin = target.origin;
28
+ else if (isIndexConstant && target.origin === "constant") origin = "constant";
29
+ else origin = "runtime";
30
+ return snip(isKnownAtComptime(target) && isKnownAtComptime(index) ? target.value[index.value] : stitch`${target}[${index}]`, elementType, origin);
31
+ }
32
+ if (isVec(target.dataType)) return snip(isKnownAtComptime(target) && isKnownAtComptime(index) ? target.value[index.value] : stitch`${target}[${index}]`, target.dataType.primitive, target.origin === "constant" || target.origin === "constant-tgpu-const-ref" ? "constant" : "runtime");
33
+ if (isPtr(target.dataType)) return accessIndex(derefSnippet(target), index);
34
+ if (target.value instanceof MatrixColumnsAccess) {
35
+ const propType = indexableTypeToResult[target.value.matrix.dataType.type];
36
+ return snip(stitch`${target.value.matrix}[${index}]`, propType, target.origin);
37
+ }
38
+ if (target.dataType.type in indexableTypeToResult) throw new Error("The only way of accessing matrix elements in TypeGPU functions is through the 'columns' property.");
39
+ if (isKnownAtComptime(target) && isKnownAtComptime(index) || target.dataType === UnknownData) return coerceToSnippet(target.value[index.value]);
40
+ if (isWgslStruct(target.dataType) && isKnownAtComptime(index) && typeof index.value === "string") return accessProp(target, index.value);
41
+ }
42
+
43
+ //#endregion
44
+ //#region src/core/valueProxyUtils.ts
45
+ const valueProxyHandler = { get(target, prop) {
46
+ if (prop in target) return Reflect.get(target, prop);
47
+ if (prop === "toString" || prop === Symbol.toStringTag || prop === Symbol.toPrimitive) return () => target.toString();
48
+ if (typeof prop === "symbol") return;
49
+ const targetSnippet = getOwnSnippet(target);
50
+ const index = Number(prop);
51
+ if (!Number.isNaN(index)) {
52
+ const accessed = accessIndex(targetSnippet, index);
53
+ if (!accessed) return;
54
+ return new Proxy({
55
+ [$internal]: true,
56
+ [$resolve]: (ctx) => ctx.resolve(accessed.value, accessed.dataType),
57
+ [$ownSnippet]: accessed,
58
+ toString: () => `${String(target)}[${prop}]`
59
+ }, valueProxyHandler);
60
+ }
61
+ const accessed = accessProp(targetSnippet, String(prop));
62
+ if (!accessed) return;
63
+ return new Proxy({
64
+ [$internal]: true,
65
+ [$resolve]: (ctx) => ctx.resolve(accessed.value, accessed.dataType),
66
+ [$ownSnippet]: accessed,
67
+ toString: () => `${String(target)}.${prop}`
68
+ }, valueProxyHandler);
69
+ } };
70
+ function getGpuValueRecursively(value) {
71
+ let unwrapped = value;
72
+ while (true) {
73
+ const gpuValue = getGPUValue(unwrapped);
74
+ if (!gpuValue) break;
75
+ unwrapped = gpuValue;
76
+ }
77
+ return unwrapped;
78
+ }
79
+
80
+ //#endregion
81
+ //#region src/core/resolve/externals.ts
82
+ /**
83
+ * Merges two external maps into one. If a key is present in both maps, the value from the new map is used.
84
+ * If the external value is a namable object, it is given a name if it does not already have one.
85
+ * @param existing - The existing external map.
86
+ * @param newExternals - The new external map.
87
+ */
88
+ function applyExternals(existing, newExternals) {
89
+ for (const [key, value] of Object.entries(newExternals)) {
90
+ existing[key] = value;
91
+ if (value && (typeof value === "object" || typeof value === "function") && getName(value) === void 0) setName(value, key);
92
+ }
93
+ }
94
+ function addArgTypesToExternals(implementation, argTypes, applyExternals) {
95
+ const argTypeNames = [...implementation.matchAll(/:\s*(?<arg>.*?)\s*[,)]/g)].map((found) => found ? found[1] : void 0);
96
+ applyExternals(Object.fromEntries(argTypes.flatMap((argType, i) => {
97
+ const argTypeName = argTypeNames ? argTypeNames[i] : void 0;
98
+ return isWgslStruct(argType) && argTypeName !== void 0 ? [[argTypeName, argType]] : [];
99
+ })));
100
+ }
101
+ function addReturnTypeToExternals(implementation, returnType, applyExternals) {
102
+ const matched = implementation.match(/->\s(?<output>[\w\d_]+)\s{/);
103
+ const outputName = matched ? matched[1]?.trim() : void 0;
104
+ if (isWgslStruct(returnType) && outputName && !/\s/g.test(outputName)) applyExternals({ [outputName]: returnType });
105
+ }
106
+ function identifierRegex(name) {
107
+ return new RegExp(`(?<![\\w\\$_.])${name.replaceAll(".", "\\.").replaceAll("$", "\\$")}(?![\\w\\$_])`, "g");
108
+ }
109
+ /**
110
+ * Replaces all occurrences of external names in WGSL code with their resolved values.
111
+ * It adds all necessary definitions to the resolution context.
112
+ * @param ctx - The resolution context.
113
+ * @param externalMap - The external map.
114
+ * @param wgsl - The WGSL code.
115
+ *
116
+ * @returns The WGSL code with all external names replaced with their resolved values.
117
+ */
118
+ function replaceExternalsInWgsl(ctx, externalMap, wgsl) {
119
+ return Object.entries(externalMap).reduce((acc, [externalName, external]) => {
120
+ const externalRegex = identifierRegex(externalName);
121
+ if (wgsl && externalName !== "Out" && externalName !== "In" && !externalRegex.test(wgsl)) console.warn(`The external '${externalName}' wasn't used in the resolved template.`);
122
+ if (isWgsl(external) || isLooseData(external) || hasTinyestMetadata(external)) return acc.replaceAll(externalRegex, ctx.resolve(external).value);
123
+ if (external !== null && typeof external === "object") {
124
+ const foundProperties = [...wgsl.matchAll(new RegExp(`${externalName.replaceAll(".", "\\.").replaceAll("$", "\\$")}\\.(?<prop>.*?)(?![\\w\\$_])`, "g"))].map((found) => found[1]);
125
+ return [...new Set(foundProperties)].reduce((innerAcc, prop) => prop && prop in external ? replaceExternalsInWgsl(ctx, { [`${externalName}.${prop}`]: external[prop] }, innerAcc) : innerAcc, acc);
126
+ }
127
+ console.warn(`During resolution, the external '${externalName}' has been omitted. Only TGPU resources, 'use gpu' functions, primitives, and plain JS objects can be used as externals.`);
128
+ return acc;
129
+ }, wgsl);
130
+ }
131
+
132
+ //#endregion
133
+ //#region src/core/function/extractArgs.ts
134
+ /**
135
+ * Extracts info about arguments of a given WGSL function string.
136
+ * @example
137
+ * const code = `
138
+ * fn add(a: i32, @location(0) b: i32, c) -> i32 {
139
+ * return a + b + c;
140
+ * }`;
141
+ *
142
+ * extractArgs(code);
143
+ * // {
144
+ * // args: [
145
+ * // { identifier: 'a', attributes: [], type: 'i32' },
146
+ * // { identifier: 'b', attributes: ['@location(0)'], type: 'i32' },
147
+ * // { identifier: 'c', attributes: [], type: undefined }
148
+ * // ],
149
+ * // ret: { type: 'i32', attributes: [] },
150
+ * // range: { begin: 11, end: 51 }
151
+ * // }
152
+ */
153
+ function extractArgs(rawCode) {
154
+ const { strippedCode, argRange: range } = strip(rawCode);
155
+ const code = new ParsableString(strippedCode);
156
+ code.consume("(");
157
+ const args = [];
158
+ while (!code.isAt(")")) {
159
+ const attributes = [];
160
+ while (code.isAt("@")) {
161
+ code.parseUntil(closingParenthesis, parentheses);
162
+ code.consume(")");
163
+ attributes.push(code.lastParsed);
164
+ }
165
+ code.parseUntil(identifierEndSymbols);
166
+ const identifier = code.lastParsed;
167
+ let maybeType;
168
+ if (code.isAt(":")) {
169
+ code.consume(":");
170
+ code.parseUntil(typeEndSymbols, angleBrackets);
171
+ maybeType = code.lastParsed;
172
+ }
173
+ args.push({
174
+ identifier,
175
+ attributes,
176
+ type: maybeType
177
+ });
178
+ if (code.isAt(",")) code.consume(",");
179
+ }
180
+ code.consume(")");
181
+ let maybeRet;
182
+ if (code.isAt("->")) {
183
+ code.consume("->");
184
+ const attributes = [];
185
+ while (code.isAt("@")) {
186
+ code.parseUntil(closingParenthesis, parentheses);
187
+ code.consume(")");
188
+ attributes.push(code.lastParsed);
189
+ }
190
+ maybeRet = {
191
+ type: code.str.slice(code.pos),
192
+ attributes
193
+ };
194
+ }
195
+ return {
196
+ args,
197
+ ret: maybeRet,
198
+ range: {
199
+ begin: range[0],
200
+ end: range[1]
201
+ }
202
+ };
203
+ }
204
+ /**
205
+ * Strips comments, whitespaces, the name and the body of the function.
206
+ * @example
207
+ * const code = `
208
+ * fn add( a, // first argument
209
+ * @location(0) b : i32 ) -> i32 {
210
+ * return a + b; // returns the sum
211
+ * }`;
212
+ *
213
+ * strip(code); // "(a,@location(0)b:i32)->i32"
214
+ */
215
+ function strip(rawCode) {
216
+ const code = new ParsableString(rawCode);
217
+ let strippedCode = "";
218
+ let argsStart;
219
+ while (!code.isFinished()) {
220
+ if (code.isAt(blankSpaces)) {
221
+ code.advanceBy(1);
222
+ continue;
223
+ }
224
+ if (code.isAt("//")) {
225
+ code.consume("//");
226
+ code.parseUntil(lineBreaks);
227
+ code.advanceBy(1);
228
+ continue;
229
+ }
230
+ if (code.isAt("/*")) {
231
+ code.parseUntil(openingCommentBlock, commentBlocks);
232
+ code.consume("*/");
233
+ continue;
234
+ }
235
+ if (code.isAt("{")) return {
236
+ strippedCode,
237
+ argRange: [argsStart, code.pos]
238
+ };
239
+ if (code.isAt("(") && argsStart === void 0) argsStart = code.pos;
240
+ if (argsStart !== void 0) strippedCode += code.str[code.pos];
241
+ code.advanceBy(1);
242
+ }
243
+ throw new Error("Invalid wgsl code!");
244
+ }
245
+ var ParsableString = class {
246
+ #parseStartPos;
247
+ #pos;
248
+ constructor(str) {
249
+ this.str = str;
250
+ this.#pos = 0;
251
+ }
252
+ get pos() {
253
+ return this.#pos;
254
+ }
255
+ /**
256
+ * This property is equivalent to the substring of `this.str`
257
+ * from the position of the last `parseUntil` call, to the current position.
258
+ */
259
+ get lastParsed() {
260
+ if (this.#parseStartPos === void 0) throw new Error("Parse was not called yet!");
261
+ return this.str.slice(this.#parseStartPos, this.pos);
262
+ }
263
+ isFinished() {
264
+ return this.#pos >= this.str.length;
265
+ }
266
+ isAt(substr) {
267
+ if (typeof substr === "string") {
268
+ for (let i = 0; i < substr.length; i++) if (this.str[this.#pos + i] !== substr[i]) return false;
269
+ return true;
270
+ }
271
+ for (const elem of substr) if (this.isAt(elem)) return true;
272
+ return false;
273
+ }
274
+ /**
275
+ * @param toFind a set of strings either of which satisfy the search.
276
+ * @param brackets a pair of brackets that has to be closed for result to be valid. This includes the found character(s).
277
+ * @example
278
+ * // internal state:
279
+ * // '(@attribute(0) identifier: type)'
280
+ * // ^
281
+ * this.parse(new Set(')'), ['(', ')']);
282
+ * // internal state:
283
+ * // '(@attribute(0) identifier: type)'
284
+ * // ^
285
+ */
286
+ parseUntil(toFind, brackets) {
287
+ this.#parseStartPos = this.#pos;
288
+ let openedBrackets = 0;
289
+ while (this.#pos < this.str.length) {
290
+ if (brackets && this.isAt(brackets[0])) openedBrackets += 1;
291
+ if (brackets && this.isAt(brackets[1])) openedBrackets -= 1;
292
+ if (openedBrackets === 0) {
293
+ if (this.isAt(toFind)) return this.#pos;
294
+ }
295
+ this.#pos += 1;
296
+ }
297
+ throw new Error("Reached the end of the string without finding a match!");
298
+ }
299
+ advanceBy(steps) {
300
+ this.#pos += steps;
301
+ }
302
+ consume(str) {
303
+ if (!this.isAt(str)) throw new Error(`Expected '${str}' at position ${this.#pos}, but found '${this.str.slice(this.#pos, this.#pos + str.length)}'`);
304
+ this.advanceBy(str.length);
305
+ }
306
+ };
307
+ const lineBreaks = new Set([
308
+ "\n",
309
+ "\v",
310
+ "\f",
311
+ "\r",
312
+ "…",
313
+ "\u2028",
314
+ "\u2029"
315
+ ]);
316
+ const blankSpaces = new Set([
317
+ ...lineBreaks,
318
+ " ",
319
+ " ",
320
+ "‎",
321
+ "‏"
322
+ ]);
323
+ const closingParenthesis = new Set([")"]);
324
+ const identifierEndSymbols = new Set([
325
+ ":",
326
+ ",",
327
+ ")"
328
+ ]);
329
+ const typeEndSymbols = new Set([",", ")"]);
330
+ const openingCommentBlock = new Set(["*/"]);
331
+ const parentheses = ["(", ")"];
332
+ const angleBrackets = ["<", ">"];
333
+ const commentBlocks = ["/*", "*/"];
334
+
335
+ //#endregion
336
+ //#region src/core/function/fnCore.ts
337
+ function createFnCore(implementation, fnAttribute = "") {
338
+ /**
339
+ * External application has to be deferred until resolution because
340
+ * some externals can reference the owner function which has not been
341
+ * initialized yet (like when accessing the Output struct of a vertex
342
+ * entry fn).
343
+ */
344
+ const externalsToApply = [];
345
+ return {
346
+ [$getNameForward]: typeof implementation === "function" ? implementation : void 0,
347
+ applyExternals(newExternals) {
348
+ externalsToApply.push(newExternals);
349
+ },
350
+ resolve(ctx, argTypes, returnType) {
351
+ const externalMap = {};
352
+ for (const externals of externalsToApply) applyExternals(externalMap, externals);
353
+ const id = ctx.getUniqueName(this);
354
+ if (typeof implementation === "string") {
355
+ if (!returnType) throw new Error("Explicit return type is required for string implementation");
356
+ const replacedImpl = replaceExternalsInWgsl(ctx, externalMap, implementation);
357
+ let header = "";
358
+ let body = "";
359
+ if (fnAttribute !== "") {
360
+ const input = isWgslStruct(argTypes[0]) ? `(in: ${ctx.resolve(argTypes[0]).value})` : "()";
361
+ const attributes = isWgslData(returnType) ? getAttributesString(returnType) : "";
362
+ header = `${input} ${returnType !== Void ? isWgslStruct(returnType) ? `-> ${ctx.resolve(returnType).value}` : `-> ${attributes !== "" ? attributes : "@location(0)"} ${ctx.resolve(returnType).value}` : ""} `;
363
+ body = replacedImpl;
364
+ } else {
365
+ const providedArgs = extractArgs(replacedImpl);
366
+ if (providedArgs.args.length !== argTypes.length) throw new Error(`WGSL implementation has ${providedArgs.args.length} arguments, while the shell has ${argTypes.length} arguments.`);
367
+ header = `(${providedArgs.args.map((argInfo, i) => `${argInfo.identifier}: ${checkAndReturnType(ctx, `parameter ${argInfo.identifier}`, argInfo.type, argTypes[i])}`).join(", ")}) ${returnType === Void ? "" : `-> ${checkAndReturnType(ctx, "return type", providedArgs.ret?.type, returnType)}`}`;
368
+ body = replacedImpl.slice(providedArgs.range.end);
369
+ }
370
+ ctx.addDeclaration(`${fnAttribute}fn ${id}${header}${body}`);
371
+ return snip(id, returnType, "runtime");
372
+ }
373
+ const pluginData = getMetaData(implementation);
374
+ const pluginExternals = typeof pluginData?.externals === "function" ? pluginData.externals() : pluginData?.externals;
375
+ if (pluginExternals) applyExternals(externalMap, Object.fromEntries(Object.entries(pluginExternals).filter(([name]) => !(name in externalMap))));
376
+ const ast = pluginData?.ast;
377
+ if (!ast) throw new Error("Missing metadata for tgpu.fn function body (either missing 'use gpu' directive, or misconfigured `unplugin-typegpu`)");
378
+ const missingExternals = ast.externalNames.filter((name) => !(name in externalMap));
379
+ if (missingExternals.length > 0) throw new MissingLinksError(getName(this), missingExternals);
380
+ const maybeSecondArg = ast.params[1];
381
+ if (maybeSecondArg && maybeSecondArg.type === "i" && fnAttribute !== "") applyExternals(externalMap, { [maybeSecondArg.name]: undecorate(returnType) });
382
+ const { head, body, returnType: actualReturnType } = ctx.fnToWgsl({
383
+ functionType: fnAttribute.includes("@compute") ? "compute" : fnAttribute.includes("@vertex") ? "vertex" : fnAttribute.includes("@fragment") ? "fragment" : "normal",
384
+ argTypes,
385
+ params: ast.params,
386
+ returnType,
387
+ body: ast.body,
388
+ externalMap
389
+ });
390
+ ctx.addDeclaration(`${fnAttribute}fn ${id}${ctx.resolve(head).value}${ctx.resolve(body).value}`);
391
+ return snip(id, actualReturnType, "runtime");
392
+ }
393
+ };
394
+ }
395
+ function checkAndReturnType(ctx, name, wgslType, jsType) {
396
+ const resolvedJsType = ctx.resolve(jsType).value.replace(/\s/g, "");
397
+ if (!wgslType) return resolvedJsType;
398
+ const resolvedWgslType = wgslType.replace(/\s/g, "");
399
+ if (resolvedWgslType !== resolvedJsType) throw new Error(`Type mismatch between TGPU shell and WGSL code string: ${name}, JS type "${resolvedJsType}", WGSL type "${resolvedWgslType}".`);
400
+ return wgslType;
401
+ }
402
+
403
+ //#endregion
404
+ //#region src/core/function/templateUtils.ts
405
+ function stripTemplate(arg, ...values) {
406
+ return isTemplateStringsArray(arg) ? templateLiteralIdentity(arg, ...values) : arg;
407
+ }
408
+ function isTemplateStringsArray(value) {
409
+ return Array.isArray(value) && "raw" in value && Array.isArray(value.raw) && value.raw.every((item) => typeof item === "string");
410
+ }
411
+ function templateLiteralIdentity(strings, ...values) {
412
+ return strings.slice(1).reduce((acc, elem, index) => `${acc}${values[index]}${elem}`, strings[0]);
413
+ }
414
+
415
+ //#endregion
416
+ //#region src/core/slot/slot.ts
417
+ function slot(defaultValue) {
418
+ return new TgpuSlotImpl(defaultValue);
419
+ }
420
+ var TgpuSlotImpl = class {
421
+ [$internal] = true;
422
+ resourceType = "slot";
423
+ constructor(defaultValue = void 0) {
424
+ this.defaultValue = defaultValue;
425
+ }
426
+ $name(label) {
427
+ setName(this, label);
428
+ return this;
429
+ }
430
+ areEqual(a, b) {
431
+ return Object.is(a, b);
432
+ }
433
+ toString() {
434
+ return `slot:${getName(this) ?? "<unnamed>"}`;
435
+ }
436
+ get [$gpuValueOf]() {
437
+ const ctx = getResolutionCtx();
438
+ if (!ctx) throw new Error(`Cannot access tgpu.slot's value outside of resolution.`);
439
+ return getGpuValueRecursively(ctx.unwrap(this));
440
+ }
441
+ get value() {
442
+ return this[$gpuValueOf];
443
+ }
444
+ get $() {
445
+ return this.value;
446
+ }
447
+ };
448
+
449
+ //#endregion
450
+ //#region src/core/slot/internalSlots.ts
451
+ const shaderStageSlot = slot(void 0);
452
+
453
+ //#endregion
454
+ //#region src/core/function/tgpuVertexFn.ts
455
+ /**
456
+ * Creates a shell of a typed entry function for the vertex shader stage. Any function
457
+ * that implements this shell can run for each vertex, allowing the inner code to process
458
+ * attributes and determine the final position of the vertex.
459
+ *
460
+ * @param options.in
461
+ * Vertex attributes and builtins to be made available to functions that implement this shell.
462
+ * @param options.out
463
+ * A record containing the final position of the vertex, and any information
464
+ * passed onto the fragment shader stage.
465
+ */
466
+ function vertexFn(options) {
467
+ if (Object.keys(options.out).length === 0) throw new Error(`A vertexFn output cannot be empty since it must include the 'position' builtin.`);
468
+ const shell = {
469
+ in: options.in,
470
+ out: options.out,
471
+ argTypes: options.in && Object.keys(options.in).length !== 0 ? [createIoSchema(options.in)] : [],
472
+ entryPoint: "vertex"
473
+ };
474
+ const call = (arg, ...values) => createVertexFn(shell, stripTemplate(arg, ...values));
475
+ return Object.assign(call, shell);
476
+ }
477
+ function isTgpuVertexFn(value) {
478
+ return value?.shell?.entryPoint === "vertex";
479
+ }
480
+ function createVertexFn(shell, implementation) {
481
+ const core = createFnCore(implementation, "@vertex ");
482
+ const inputType = shell.argTypes[0];
483
+ return {
484
+ shell,
485
+ $uses(newExternals) {
486
+ core.applyExternals(newExternals);
487
+ return this;
488
+ },
489
+ [$internal]: true,
490
+ [$getNameForward]: core,
491
+ $name(newLabel) {
492
+ setName(this, newLabel);
493
+ if (isNamable(inputType)) inputType.$name(`${newLabel}_Input`);
494
+ return this;
495
+ },
496
+ [$resolve](ctx) {
497
+ const outputWithLocation = createIoSchema(shell.out, ctx.varyingLocations).$name(`${getName(this) ?? ""}_Output`);
498
+ if (typeof implementation === "string") {
499
+ if (inputType) core.applyExternals({ In: inputType });
500
+ core.applyExternals({ Out: outputWithLocation });
501
+ }
502
+ return ctx.withSlots([[shaderStageSlot, "vertex"]], () => core.resolve(ctx, shell.argTypes, outputWithLocation));
503
+ },
504
+ toString() {
505
+ return `vertexFn:${getName(core) ?? "<unnamed>"}`;
506
+ }
507
+ };
508
+ }
509
+
510
+ //#endregion
511
+ //#region src/common/fullScreenTriangle.ts
512
+ /**
513
+ * A vertex function that defines a single full-screen triangle out
514
+ * of three points.
515
+ *
516
+ * @example
517
+ * ```ts
518
+ * import { common } from 'typegpu';
519
+ *
520
+ * const pipeline = root.createRenderPipeline({
521
+ * vertex: common.fullScreenTriangle,
522
+ * fragment: yourFragmentShader,
523
+ * });
524
+ *
525
+ * pipeline.draw(3);
526
+ * ```
527
+ */
528
+ const fullScreenTriangle = vertexFn({
529
+ in: { vertexIndex: builtin.vertexIndex },
530
+ out: {
531
+ pos: builtin.position,
532
+ uv: vec2f
533
+ }
534
+ })`{
535
+ const pos = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
536
+ const uv = array<vec2f, 3>(vec2f(0, 1), vec2f(2, 1), vec2f(0, -1));
537
+
538
+ return Out(vec4f(pos[in.vertexIndex], 0, 1), uv[in.vertexIndex]);
539
+ }`;
540
+
541
+ //#endregion
542
+ export { slot as a, addArgTypesToExternals as c, replaceExternalsInWgsl as d, getGpuValueRecursively as f, shaderStageSlot as i, addReturnTypeToExternals as l, accessIndex as m, isTgpuVertexFn as n, stripTemplate as o, valueProxyHandler as p, vertexFn as r, createFnCore as s, fullScreenTriangle as t, applyExternals as u };
543
+ //# sourceMappingURL=fullScreenTriangle-MdLGaAMR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fullScreenTriangle-MdLGaAMR.js","names":["#pos","#parseStartPos"],"sources":["../src/getGPUValue.ts","../src/tgsl/accessIndex.ts","../src/core/valueProxyUtils.ts","../src/core/resolve/externals.ts","../src/core/function/extractArgs.ts","../src/core/function/fnCore.ts","../src/core/function/templateUtils.ts","../src/core/slot/slot.ts","../src/core/slot/internalSlots.ts","../src/core/function/tgpuVertexFn.ts","../src/common/fullScreenTriangle.ts"],"sourcesContent":["import { $gpuValueOf } from './shared/symbols.ts';\nimport type { WithGPUValue } from './types.ts';\n\nexport function getGPUValue(\n object: unknown,\n): unknown {\n return (object as WithGPUValue<unknown>)?.[$gpuValueOf];\n}\n","import { stitch } from '../core/resolve/stitch.ts';\nimport {\n isDisarray,\n MatrixColumnsAccess,\n UnknownData,\n} from '../data/dataTypes.ts';\nimport { derefSnippet } from '../data/ref.ts';\nimport {\n isEphemeralSnippet,\n type Origin,\n snip,\n type Snippet,\n} from '../data/snippet.ts';\nimport { vec2f, vec3f, vec4f } from '../data/vector.ts';\nimport {\n type BaseData,\n isNaturallyEphemeral,\n isPtr,\n isVec,\n isWgslArray,\n isWgslStruct,\n} from '../data/wgslTypes.ts';\nimport { isKnownAtComptime } from '../types.ts';\nimport { accessProp } from './accessProp.ts';\nimport { coerceToSnippet } from './generationHelpers.ts';\n\nconst indexableTypeToResult = {\n mat2x2f: vec2f,\n mat3x3f: vec3f,\n mat4x4f: vec4f,\n} as const;\n\nexport function accessIndex(\n target: Snippet,\n indexArg: Snippet | number,\n): Snippet | undefined {\n const index = typeof indexArg === 'number'\n ? coerceToSnippet(indexArg)\n : indexArg;\n\n // array\n if (isWgslArray(target.dataType) || isDisarray(target.dataType)) {\n const elementType = target.dataType.elementType;\n const isElementNatEph = isNaturallyEphemeral(elementType);\n const isTargetEphemeral = isEphemeralSnippet(target);\n const isIndexConstant = index.origin === 'constant';\n\n let origin: Origin;\n\n if (target.origin === 'constant-tgpu-const-ref') {\n // Constant refs stay const unless the element/index forces runtime materialization\n if (isIndexConstant) {\n origin = isElementNatEph ? 'constant' : 'constant-tgpu-const-ref';\n } else {\n origin = isElementNatEph ? 'runtime' : 'runtime-tgpu-const-ref';\n }\n } else if (target.origin === 'runtime-tgpu-const-ref') {\n // Runtime refs keep their ref semantics unless the element is ephemeral only\n origin = isElementNatEph ? 'runtime' : 'runtime-tgpu-const-ref';\n } else if (!isTargetEphemeral && !isElementNatEph) {\n // Stable containers can forward their origin information\n origin = target.origin;\n } else if (isIndexConstant && target.origin === 'constant') {\n // Plain constants indexed with constants stay constant\n origin = 'constant';\n } else {\n // Everything else must be produced at runtime\n origin = 'runtime';\n }\n\n return snip(\n isKnownAtComptime(target) && isKnownAtComptime(index)\n // oxlint-disable-next-line typescript/no-explicit-any it's fine, it's there\n ? (target.value as any)[index.value as number]\n : stitch`${target}[${index}]`,\n elementType,\n /* origin */ origin,\n );\n }\n\n // vector\n if (isVec(target.dataType)) {\n return snip(\n isKnownAtComptime(target) && isKnownAtComptime(index)\n // oxlint-disable-next-line typescript/no-explicit-any it's fine, it's there\n ? (target.value as any)[index.value as any]\n : stitch`${target}[${index}]`,\n target.dataType.primitive,\n /* origin */ target.origin === 'constant' ||\n target.origin === 'constant-tgpu-const-ref'\n ? 'constant'\n : 'runtime',\n );\n }\n\n if (isPtr(target.dataType)) {\n // Sometimes values that are typed as pointers aren't instances of `d.ref`, so we\n // allow indexing as if it wasn't a pointer.\n return accessIndex(derefSnippet(target), index);\n }\n\n // matrix.columns\n if (target.value instanceof MatrixColumnsAccess) {\n const propType = indexableTypeToResult[\n (target.value.matrix.dataType as BaseData)\n .type as keyof typeof indexableTypeToResult\n ];\n\n return snip(\n stitch`${target.value.matrix}[${index}]`,\n propType,\n /* origin */ target.origin,\n );\n }\n\n // matrix\n if ((target.dataType as BaseData).type in indexableTypeToResult) {\n throw new Error(\n \"The only way of accessing matrix elements in TypeGPU functions is through the 'columns' property.\",\n );\n }\n\n if (\n (isKnownAtComptime(target) && isKnownAtComptime(index)) ||\n target.dataType === UnknownData\n ) {\n // No idea what the type is, so we act on the snippet's value and try to guess\n return coerceToSnippet(\n // oxlint-disable-next-line typescript/no-explicit-any we're inspecting the value, and it could be any value\n (target.value as any)[index.value as number],\n );\n }\n\n if (\n isWgslStruct(target.dataType) && isKnownAtComptime(index) &&\n typeof index.value === 'string'\n ) {\n return accessProp(target, index.value);\n }\n\n return undefined;\n}\n","import type { Snippet } from '../data/snippet.ts';\nimport { getGPUValue } from '../getGPUValue.ts';\nimport { $internal, $ownSnippet, $resolve } from '../shared/symbols.ts';\nimport { accessIndex } from '../tgsl/accessIndex.ts';\nimport { accessProp } from '../tgsl/accessProp.ts';\nimport {\n getOwnSnippet,\n type SelfResolvable,\n type WithOwnSnippet,\n} from '../types.ts';\n\nexport const valueProxyHandler: ProxyHandler<\n SelfResolvable & WithOwnSnippet\n> = {\n get(target, prop) {\n if (prop in target) {\n return Reflect.get(target, prop);\n }\n\n if (\n prop === 'toString' ||\n prop === Symbol.toStringTag ||\n prop === Symbol.toPrimitive\n ) {\n return () => target.toString();\n }\n\n if (typeof prop === 'symbol') {\n return undefined;\n }\n\n const targetSnippet = getOwnSnippet(target) as Snippet;\n\n const index = Number(prop);\n if (!Number.isNaN(index)) {\n const accessed = accessIndex(targetSnippet, index);\n if (!accessed) {\n // Prop was not found, must be missing from this object\n return undefined;\n }\n\n return new Proxy({\n [$internal]: true,\n [$resolve]: (ctx) => ctx.resolve(accessed.value, accessed.dataType),\n [$ownSnippet]: accessed,\n toString: () => `${String(target)}[${prop}]`,\n }, valueProxyHandler);\n }\n\n const accessed = accessProp(targetSnippet, String(prop));\n if (!accessed) {\n // Prop was not found, must be missing from this object\n return undefined;\n }\n\n return new Proxy({\n [$internal]: true,\n [$resolve]: (ctx) => ctx.resolve(accessed.value, accessed.dataType),\n [$ownSnippet]: accessed,\n toString: () => `${String(target)}.${prop}`,\n }, valueProxyHandler);\n },\n};\n\nexport function getGpuValueRecursively<T>(value: unknown): T {\n let unwrapped = value;\n\n while (true) {\n const gpuValue = getGPUValue(unwrapped);\n if (!gpuValue) {\n break;\n }\n unwrapped = gpuValue;\n }\n\n return unwrapped as T;\n}\n","import { isLooseData } from '../../data/dataTypes.ts';\nimport { isWgslStruct } from '../../data/wgslTypes.ts';\nimport { getName, hasTinyestMetadata, setName } from '../../shared/meta.ts';\nimport { isWgsl, type ResolutionCtx } from '../../types.ts';\n\n/**\n * A key-value mapping where keys represent identifiers within shader code,\n * and values can be any type that can be resolved to a code string.\n */\nexport type ExternalMap = Record<string, unknown>;\n\n/**\n * Merges two external maps into one. If a key is present in both maps, the value from the new map is used.\n * If the external value is a namable object, it is given a name if it does not already have one.\n * @param existing - The existing external map.\n * @param newExternals - The new external map.\n */\nexport function applyExternals(\n existing: ExternalMap,\n newExternals: ExternalMap,\n) {\n for (const [key, value] of Object.entries(newExternals)) {\n existing[key] = value;\n\n // Giving name to external value, if it does not already have one.\n if (\n value && (typeof value === 'object' || typeof value === 'function') &&\n getName(value) === undefined\n ) {\n setName(value, key);\n }\n }\n}\n\nexport function addArgTypesToExternals(\n implementation: string,\n argTypes: unknown[],\n applyExternals: (externals: ExternalMap) => void,\n) {\n const argTypeNames = [\n ...implementation.matchAll(/:\\s*(?<arg>.*?)\\s*[,)]/g),\n ].map((found) => (found ? found[1] : undefined));\n\n applyExternals(\n Object.fromEntries(\n argTypes.flatMap((argType, i) => {\n const argTypeName = argTypeNames ? argTypeNames[i] : undefined;\n return isWgslStruct(argType) && argTypeName !== undefined\n ? [[argTypeName, argType]]\n : [];\n }),\n ),\n );\n}\n\nexport function addReturnTypeToExternals(\n implementation: string,\n returnType: unknown,\n applyExternals: (externals: ExternalMap) => void,\n) {\n const matched = implementation.match(/->\\s(?<output>[\\w\\d_]+)\\s{/);\n const outputName = matched ? matched[1]?.trim() : undefined;\n\n if (isWgslStruct(returnType) && outputName && !/\\s/g.test(outputName)) {\n applyExternals({ [outputName]: returnType });\n }\n}\n\nfunction identifierRegex(name: string) {\n return new RegExp(\n `(?<![\\\\w\\\\$_.])${\n name.replaceAll('.', '\\\\.').replaceAll('$', '\\\\$')\n }(?![\\\\w\\\\$_])`,\n 'g',\n );\n}\n\n/**\n * Replaces all occurrences of external names in WGSL code with their resolved values.\n * It adds all necessary definitions to the resolution context.\n * @param ctx - The resolution context.\n * @param externalMap - The external map.\n * @param wgsl - The WGSL code.\n *\n * @returns The WGSL code with all external names replaced with their resolved values.\n */\nexport function replaceExternalsInWgsl(\n ctx: ResolutionCtx,\n externalMap: ExternalMap,\n wgsl: string,\n): string {\n return Object.entries(externalMap).reduce((acc, [externalName, external]) => {\n const externalRegex = identifierRegex(externalName);\n if (\n wgsl &&\n externalName !== 'Out' &&\n externalName !== 'In' &&\n !externalRegex.test(wgsl)\n ) {\n console.warn(\n `The external '${externalName}' wasn't used in the resolved template.`,\n );\n // continue anyway, we still might need to resolve the external\n }\n\n if (\n isWgsl(external) || isLooseData(external) || hasTinyestMetadata(external)\n ) {\n return acc.replaceAll(externalRegex, ctx.resolve(external).value);\n }\n\n if (external !== null && typeof external === 'object') {\n const foundProperties = [\n ...wgsl.matchAll(\n new RegExp(\n `${\n externalName.replaceAll('.', '\\\\.').replaceAll('$', '\\\\$')\n }\\\\.(?<prop>.*?)(?![\\\\w\\\\$_])`,\n 'g',\n ),\n ),\n ].map((found) => found[1]);\n const uniqueProperties = [...new Set(foundProperties)];\n\n return uniqueProperties.reduce(\n (innerAcc: string, prop) =>\n prop && prop in external\n ? replaceExternalsInWgsl(\n ctx,\n {\n [`${externalName}.${prop}`]:\n external[prop as keyof typeof external],\n },\n innerAcc,\n )\n : innerAcc,\n acc,\n );\n }\n\n console.warn(\n `During resolution, the external '${externalName}' has been omitted. Only TGPU resources, 'use gpu' functions, primitives, and plain JS objects can be used as externals.`,\n );\n\n return acc;\n }, wgsl);\n}\n","interface FunctionArgsInfo {\n args: ArgInfo[];\n ret: ReturnInfo | undefined;\n range: {\n begin: number;\n end: number;\n };\n}\n\ninterface ArgInfo {\n identifier: string;\n attributes: string[];\n type: string | undefined;\n}\n\ninterface ReturnInfo {\n attributes: string[];\n type: string;\n}\n\n/**\n * Extracts info about arguments of a given WGSL function string.\n * @example\n * const code = `\n * fn add(a: i32, @location(0) b: i32, c) -> i32 {\n * return a + b + c;\n * }`;\n *\n * extractArgs(code);\n * // {\n * // args: [\n * // { identifier: 'a', attributes: [], type: 'i32' },\n * // { identifier: 'b', attributes: ['@location(0)'], type: 'i32' },\n * // { identifier: 'c', attributes: [], type: undefined }\n * // ],\n * // ret: { type: 'i32', attributes: [] },\n * // range: { begin: 11, end: 51 }\n * // }\n */\nexport function extractArgs(rawCode: string): FunctionArgsInfo {\n const { strippedCode, argRange: range } = strip(rawCode);\n const code = new ParsableString(strippedCode);\n code.consume('(');\n\n const args: ArgInfo[] = [];\n while (!code.isAt(')')) {\n // In each loop iteration, process all the attributes, the identifier and the potential type of a single argument.\n\n const attributes = [];\n while (code.isAt('@')) {\n code.parseUntil(closingParenthesis, parentheses);\n code.consume(')');\n attributes.push(code.lastParsed);\n }\n\n code.parseUntil(identifierEndSymbols);\n const identifier = code.lastParsed;\n\n let maybeType: string | undefined;\n if (code.isAt(':')) {\n code.consume(':');\n code.parseUntil(typeEndSymbols, angleBrackets);\n maybeType = code.lastParsed;\n }\n\n args.push({\n identifier,\n attributes,\n type: maybeType,\n });\n\n if (code.isAt(',')) {\n code.consume(',');\n }\n }\n code.consume(')');\n\n let maybeRet: ReturnInfo | undefined;\n if (code.isAt('->')) {\n code.consume('->');\n\n const attributes = [];\n while (code.isAt('@')) {\n code.parseUntil(closingParenthesis, parentheses);\n code.consume(')');\n attributes.push(code.lastParsed);\n }\n\n maybeRet = { type: code.str.slice(code.pos), attributes };\n }\n\n return {\n args,\n ret: maybeRet,\n range: { begin: range[0], end: range[1] },\n };\n}\n\n/**\n * Strips comments, whitespaces, the name and the body of the function.\n * @example\n * const code = `\n * fn add( a, // first argument\n * @location(0) b : i32 ) -> i32 {\n * return a + b; // returns the sum\n * }`;\n *\n * strip(code); // \"(a,@location(0)b:i32)->i32\"\n */\nfunction strip(\n rawCode: string,\n): { strippedCode: string; argRange: [number, number] } {\n const code = new ParsableString(rawCode);\n let strippedCode = '';\n let argsStart: number | undefined;\n\n while (!code.isFinished()) {\n // parse character by character while ignoring comments and blankspaces until you find a `{`.\n\n // skip any blankspace\n if (code.isAt(blankSpaces)) {\n code.advanceBy(1); // the blankspace character\n continue;\n }\n\n // skip line comments\n if (code.isAt('//')) {\n code.consume('//');\n code.parseUntil(lineBreaks);\n code.advanceBy(1); // the line break\n continue;\n }\n\n // skip block comments\n if (code.isAt('/*')) {\n code.parseUntil(openingCommentBlock, commentBlocks);\n code.consume('*/');\n continue;\n }\n\n if (code.isAt('{')) {\n return {\n strippedCode,\n argRange: [argsStart as number, code.pos],\n };\n }\n\n if (code.isAt('(') && argsStart === undefined) {\n argsStart = code.pos;\n }\n\n if (argsStart !== undefined) {\n strippedCode += code.str[code.pos];\n }\n code.advanceBy(1); // parsed character\n }\n throw new Error('Invalid wgsl code!');\n}\n\nclass ParsableString {\n #parseStartPos: number | undefined;\n #pos: number;\n constructor(public readonly str: string) {\n this.#pos = 0;\n }\n\n get pos(): number {\n return this.#pos;\n }\n\n /**\n * This property is equivalent to the substring of `this.str`\n * from the position of the last `parseUntil` call, to the current position.\n */\n get lastParsed(): string {\n if (this.#parseStartPos === undefined) {\n throw new Error('Parse was not called yet!');\n }\n return this.str.slice(this.#parseStartPos, this.pos);\n }\n\n isFinished() {\n return this.#pos >= this.str.length;\n }\n\n isAt(substr: string | Set<string>): boolean {\n if (typeof substr === 'string') {\n for (let i = 0; i < substr.length; i++) {\n if (this.str[this.#pos + i] !== substr[i]) {\n return false;\n }\n }\n return true;\n }\n for (const elem of substr) {\n if (this.isAt(elem)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @param toFind a set of strings either of which satisfy the search.\n * @param brackets a pair of brackets that has to be closed for result to be valid. This includes the found character(s).\n * @example\n * // internal state:\n * // '(@attribute(0) identifier: type)'\n * // ^\n * this.parse(new Set(')'), ['(', ')']);\n * // internal state:\n * // '(@attribute(0) identifier: type)'\n * // ^\n */\n parseUntil(\n toFind: Set<string>,\n brackets?: readonly [string, string],\n ): number {\n this.#parseStartPos = this.#pos;\n let openedBrackets = 0;\n while (this.#pos < this.str.length) {\n if (brackets && this.isAt(brackets[0])) {\n openedBrackets += 1;\n }\n if (brackets && this.isAt(brackets[1])) {\n openedBrackets -= 1;\n }\n if (openedBrackets === 0) {\n if (this.isAt(toFind)) {\n return this.#pos;\n }\n }\n this.#pos += 1;\n }\n throw new Error('Reached the end of the string without finding a match!');\n }\n\n advanceBy(steps: number) {\n this.#pos += steps;\n }\n\n consume(str: string): void {\n if (!this.isAt(str)) {\n throw new Error(\n `Expected '${str}' at position ${this.#pos}, but found '${\n this.str.slice(this.#pos, this.#pos + str.length)\n }'`,\n );\n }\n this.advanceBy(str.length);\n }\n}\n\nconst lineBreaks = new Set<string>([\n '\\u000A', // line feed\n '\\u000B', // vertical tab\n '\\u000C', // form feed\n '\\u000D', // carriage return\n '\\u0085', // next line\n '\\u2028', // line separator\n '\\u2029', // paragraph separator\n]);\nconst blankSpaces = new Set<string>([\n ...lineBreaks,\n '\\u0020', // space\n '\\u0009', // horizontal tab\n '\\u200E', // left-to-right mark\n '\\u200F', // right-to-left mark\n]);\nconst closingParenthesis = new Set<string>([')']);\nconst identifierEndSymbols = new Set([':', ',', ')']);\nconst typeEndSymbols = new Set([',', ')']);\nconst openingCommentBlock = new Set(['*/']);\n\nconst parentheses = ['(', ')'] as const;\nconst angleBrackets = ['<', '>'] as const;\nconst commentBlocks = ['/*', '*/'] as const;\n","import { getAttributesString } from '../../data/attributes.ts';\nimport { undecorate } from '../../data/dataTypes.ts';\nimport { type ResolvedSnippet, snip } from '../../data/snippet.ts';\nimport {\n type BaseData,\n isWgslData,\n isWgslStruct,\n Void,\n} from '../../data/wgslTypes.ts';\nimport { MissingLinksError } from '../../errors.ts';\nimport { getMetaData, getName } from '../../shared/meta.ts';\nimport { $getNameForward } from '../../shared/symbols.ts';\nimport type { ResolutionCtx } from '../../types.ts';\nimport {\n applyExternals,\n type ExternalMap,\n replaceExternalsInWgsl,\n} from '../resolve/externals.ts';\nimport { extractArgs } from './extractArgs.ts';\nimport type { Implementation } from './fnTypes.ts';\n\nexport interface FnCore {\n applyExternals: (newExternals: ExternalMap) => void;\n resolve(\n ctx: ResolutionCtx,\n /**\n * The argument types can be AutoStruct if they're determined based on usage\n * (like in auto-entry functions).\n */\n argTypes: BaseData[],\n /**\n * The return type of the function. If undefined, the type should be inferred\n * from the implementation (relevant for shellless functions).\n */\n returnType: BaseData | undefined,\n ): ResolvedSnippet;\n}\n\nexport function createFnCore(\n implementation: Implementation,\n fnAttribute = '',\n): FnCore {\n /**\n * External application has to be deferred until resolution because\n * some externals can reference the owner function which has not been\n * initialized yet (like when accessing the Output struct of a vertex\n * entry fn).\n */\n const externalsToApply: ExternalMap[] = [];\n\n const core = {\n // Making the implementation the holder of the name, as long as it's\n // a function (and not a string implementation)\n [$getNameForward]: typeof implementation === 'function'\n ? implementation\n : undefined,\n applyExternals(newExternals: ExternalMap): void {\n externalsToApply.push(newExternals);\n },\n\n resolve(\n ctx: ResolutionCtx,\n argTypes: BaseData[],\n returnType: BaseData | undefined,\n ): ResolvedSnippet {\n const externalMap: ExternalMap = {};\n\n for (const externals of externalsToApply) {\n applyExternals(externalMap, externals);\n }\n\n const id = ctx.getUniqueName(this);\n\n if (typeof implementation === 'string') {\n if (!returnType) {\n throw new Error(\n 'Explicit return type is required for string implementation',\n );\n }\n\n const replacedImpl = replaceExternalsInWgsl(\n ctx,\n externalMap,\n implementation,\n );\n\n let header = '';\n let body = '';\n\n if (fnAttribute !== '') {\n const input = isWgslStruct(argTypes[0])\n ? `(in: ${ctx.resolve(argTypes[0]).value})`\n : '()';\n\n const attributes = isWgslData(returnType)\n ? getAttributesString(returnType)\n : '';\n const output = returnType !== Void\n ? isWgslStruct(returnType)\n ? `-> ${ctx.resolve(returnType).value}`\n : `-> ${attributes !== '' ? attributes : '@location(0)'} ${\n ctx.resolve(returnType).value\n }`\n : '';\n\n header = `${input} ${output} `;\n body = replacedImpl;\n } else {\n const providedArgs = extractArgs(replacedImpl);\n\n if (providedArgs.args.length !== argTypes.length) {\n throw new Error(\n `WGSL implementation has ${providedArgs.args.length} arguments, while the shell has ${argTypes.length} arguments.`,\n );\n }\n\n const input = providedArgs.args.map((argInfo, i) =>\n `${argInfo.identifier}: ${\n checkAndReturnType(\n ctx,\n `parameter ${argInfo.identifier}`,\n argInfo.type,\n argTypes[i],\n )\n }`\n ).join(', ');\n\n const output = returnType === Void ? '' : `-> ${\n checkAndReturnType(\n ctx,\n 'return type',\n providedArgs.ret?.type,\n returnType,\n )\n }`;\n\n header = `(${input}) ${output}`;\n\n body = replacedImpl.slice(providedArgs.range.end);\n }\n\n ctx.addDeclaration(`${fnAttribute}fn ${id}${header}${body}`);\n return snip(id, returnType, /* origin */ 'runtime');\n }\n\n // get data generated by the plugin\n const pluginData = getMetaData(implementation);\n\n // Passing a record happens prior to version 0.9.0\n // TODO: Support for this can be removed down the line\n const pluginExternals = typeof pluginData?.externals === 'function'\n ? pluginData.externals()\n : pluginData?.externals;\n\n if (pluginExternals) {\n const missing = Object.fromEntries(\n Object.entries(pluginExternals).filter(\n ([name]) => !(name in externalMap),\n ),\n );\n\n applyExternals(externalMap, missing);\n }\n\n const ast = pluginData?.ast;\n if (!ast) {\n throw new Error(\n \"Missing metadata for tgpu.fn function body (either missing 'use gpu' directive, or misconfigured `unplugin-typegpu`)\",\n );\n }\n\n // verify all required externals are present\n const missingExternals = ast.externalNames.filter(\n (name) => !(name in externalMap),\n );\n if (missingExternals.length > 0) {\n throw new MissingLinksError(getName(this), missingExternals);\n }\n\n // If an entrypoint implementation has a second argument, it represents the output schema.\n // We look at the identifier chosen by the user and add it to externals.\n const maybeSecondArg = ast.params[1];\n if (\n maybeSecondArg && maybeSecondArg.type === 'i' && fnAttribute !== ''\n ) {\n applyExternals(\n externalMap,\n {\n // oxlint-disable-next-line typescript/no-non-null-assertion entry functions cannot be shellless\n [maybeSecondArg.name]: undecorate(returnType!),\n },\n );\n }\n\n // generate wgsl string\n\n const { head, body, returnType: actualReturnType } = ctx.fnToWgsl({\n functionType: fnAttribute.includes('@compute')\n ? 'compute'\n : fnAttribute.includes('@vertex')\n ? 'vertex'\n : fnAttribute.includes('@fragment')\n ? 'fragment'\n : 'normal',\n argTypes,\n params: ast.params,\n returnType,\n body: ast.body,\n externalMap,\n });\n\n ctx.addDeclaration(\n `${fnAttribute}fn ${id}${ctx.resolve(head).value}${\n ctx.resolve(body).value\n }`,\n );\n\n return snip(id, actualReturnType, /* origin */ 'runtime');\n },\n };\n\n return core;\n}\n\nfunction checkAndReturnType(\n ctx: ResolutionCtx,\n name: string,\n wgslType: string | undefined,\n jsType: unknown,\n) {\n const resolvedJsType = ctx.resolve(jsType).value.replace(/\\s/g, '');\n\n if (!wgslType) {\n return resolvedJsType;\n }\n\n const resolvedWgslType = wgslType.replace(/\\s/g, '');\n\n if (resolvedWgslType !== resolvedJsType) {\n throw new Error(\n `Type mismatch between TGPU shell and WGSL code string: ${name}, JS type \"${resolvedJsType}\", WGSL type \"${resolvedWgslType}\".`,\n );\n }\n\n return wgslType;\n}\n","import type { Implementation } from './fnTypes.ts';\n\nexport function stripTemplate(\n arg: Implementation | TemplateStringsArray,\n ...values: unknown[]\n): Implementation {\n return isTemplateStringsArray(arg)\n ? templateLiteralIdentity(arg, ...values)\n : arg;\n}\n\nfunction isTemplateStringsArray(value: unknown): value is TemplateStringsArray {\n return (\n Array.isArray(value) &&\n 'raw' in value &&\n Array.isArray(value.raw) &&\n value.raw.every((item) => typeof item === 'string')\n );\n}\n\nfunction templateLiteralIdentity(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): string {\n return strings\n .slice(1)\n .reduce(\n (acc, elem, index) => `${acc}${values[index]}${elem}`,\n strings[0] as string,\n );\n}\n","import { getResolutionCtx } from '../../execMode.ts';\nimport { getName, setName } from '../../shared/meta.ts';\nimport type { GPUValueOf } from '../../shared/repr.ts';\nimport { $gpuValueOf, $internal } from '../../shared/symbols.ts';\nimport { getGpuValueRecursively } from '../valueProxyUtils.ts';\nimport type { TgpuSlot } from './slotTypes.ts';\n\n// ----------\n// Public API\n// ----------\n\nexport function slot<T>(defaultValue?: T): TgpuSlot<T> {\n return new TgpuSlotImpl(defaultValue);\n}\n\n// --------------\n// Implementation\n// --------------\n\nclass TgpuSlotImpl<T> implements TgpuSlot<T> {\n public readonly [$internal] = true;\n public readonly resourceType = 'slot';\n\n constructor(public defaultValue: T | undefined = undefined) {}\n\n $name(label: string) {\n setName(this, label);\n return this;\n }\n\n areEqual(a: T, b: T): boolean {\n return Object.is(a, b);\n }\n\n toString(): string {\n return `slot:${getName(this) ?? '<unnamed>'}`;\n }\n\n get [$gpuValueOf](): GPUValueOf<T> {\n const ctx = getResolutionCtx();\n if (!ctx) {\n throw new Error(`Cannot access tgpu.slot's value outside of resolution.`);\n }\n\n return getGpuValueRecursively(ctx.unwrap(this));\n }\n\n get value(): GPUValueOf<T> {\n return this[$gpuValueOf];\n }\n\n get $(): GPUValueOf<T> {\n return this.value;\n }\n}\n","import type { ShaderStage } from '../../types.ts';\nimport { slot } from './slot.ts';\n\nexport const shaderStageSlot = slot<ShaderStage>(undefined);\n","import type {\n AnyVertexInputBuiltin,\n AnyVertexOutputBuiltin,\n OmitBuiltins,\n} from '../../builtin.ts';\nimport type { UndecorateRecord } from '../../data/dataTypes.ts';\nimport type { ResolvedSnippet } from '../../data/snippet.ts';\nimport type {\n BaseData,\n Decorated,\n Interpolate,\n Location,\n} from '../../data/wgslTypes.ts';\nimport {\n getName,\n isNamable,\n setName,\n type TgpuNamable,\n} from '../../shared/meta.ts';\nimport { $getNameForward, $internal, $resolve } from '../../shared/symbols.ts';\nimport type { Prettify } from '../../shared/utilityTypes.ts';\nimport type { ResolutionCtx, SelfResolvable } from '../../types.ts';\nimport { shaderStageSlot } from '../slot/internalSlots.ts';\nimport { createFnCore, type FnCore } from './fnCore.ts';\nimport type {\n BaseIOData,\n Implementation,\n InferIO,\n IORecord,\n} from './fnTypes.ts';\nimport { createIoSchema, type IOLayoutToSchema } from './ioSchema.ts';\nimport { stripTemplate } from './templateUtils.ts';\n\n// ----------\n// Public API\n// ----------\n\ntype VertexInConstrained = IORecord<\n BaseIOData | Decorated<BaseIOData, Location[]> | AnyVertexInputBuiltin\n>;\n\ntype VertexOutConstrained = IORecord<\n | BaseIOData\n | Decorated<BaseIOData, (Location | Interpolate)[]>\n | AnyVertexOutputBuiltin\n>;\n\n/**\n * Describes a vertex entry function signature (its arguments, return type and attributes)\n */\ntype TgpuVertexFnShellHeader<\n VertexIn extends TgpuVertexFn.In,\n VertexOut extends TgpuVertexFn.Out,\n> = {\n readonly in: VertexIn | undefined;\n readonly out: VertexOut;\n readonly argTypes: [IOLayoutToSchema<VertexIn>] | [];\n readonly entryPoint: 'vertex';\n};\n\ntype CleanIO<T> = T extends Record<string, BaseData>\n ? Prettify<UndecorateRecord<OmitBuiltins<T>>>\n : Prettify<UndecorateRecord<OmitBuiltins<{ a: T }>>> extends\n { a: infer Result } ? Result\n : never;\n\n/**\n * Describes a vertex entry function signature (its arguments, return type and attributes).\n * Allows creating tgpu vertex functions by calling this shell\n * and passing the implementation (as WGSL string or JS function) as the argument.\n */\nexport interface TgpuVertexFnShell<\n // We force the variance to be covariant, since shells are just containers of\n // schemas that coincidentally can be called to create a vertex function.\n // @ts-expect-error: We override the variance\n out TIn extends TgpuVertexFn.In,\n // @ts-expect-error: We override the variance\n out TOut extends TgpuVertexFn.Out,\n> extends TgpuVertexFnShellHeader<TIn, TOut> {\n (\n implementation: (\n input: InferIO<TIn>,\n out: IOLayoutToSchema<TOut>,\n ) => InferIO<TOut>,\n ): TgpuVertexFn<CleanIO<TIn>, CleanIO<TOut>>;\n (\n implementation: string,\n ): TgpuVertexFn<CleanIO<TIn>, CleanIO<TOut>>;\n (\n strings: TemplateStringsArray,\n ...values: unknown[]\n ): TgpuVertexFn<CleanIO<TIn>, CleanIO<TOut>>;\n}\n\nexport interface TgpuVertexFn<\n // @ts-expect-error: We override the variance\n in VertexIn extends TgpuVertexFn.In = Record<string, never>,\n out VertexOut extends TgpuVertexFn.Out = TgpuVertexFn.Out,\n> extends TgpuNamable {\n readonly [$internal]: true;\n readonly shell: TgpuVertexFnShellHeader<VertexIn, VertexOut>;\n $uses(dependencyMap: Record<string, unknown>): this;\n}\n\nexport declare namespace TgpuVertexFn {\n type In = BaseData | Record<string, BaseData>;\n type Out = Record<string, BaseData>;\n}\n\nexport function vertexFn<VertexOut extends VertexOutConstrained>(options: {\n out: VertexOut;\n}): TgpuVertexFnShell<{}, VertexOut>;\n\nexport function vertexFn<\n VertexIn extends VertexInConstrained,\n // Not allowing single-value output, as it is better practice\n // to properly label what the vertex shader is outputting.\n VertexOut extends VertexOutConstrained,\n>(options: {\n in: VertexIn;\n out: VertexOut;\n}): TgpuVertexFnShell<VertexIn, VertexOut>;\n\n/**\n * Creates a shell of a typed entry function for the vertex shader stage. Any function\n * that implements this shell can run for each vertex, allowing the inner code to process\n * attributes and determine the final position of the vertex.\n *\n * @param options.in\n * Vertex attributes and builtins to be made available to functions that implement this shell.\n * @param options.out\n * A record containing the final position of the vertex, and any information\n * passed onto the fragment shader stage.\n */\nexport function vertexFn<\n VertexIn extends VertexInConstrained,\n // Not allowing single-value output, as it is better practice\n // to properly label what the vertex shader is outputting.\n VertexOut extends VertexOutConstrained,\n>(options: {\n in?: VertexIn;\n out: VertexOut;\n}): TgpuVertexFnShell<VertexIn, VertexOut> {\n if (Object.keys(options.out).length === 0) {\n throw new Error(\n `A vertexFn output cannot be empty since it must include the 'position' builtin.`,\n );\n }\n const shell: TgpuVertexFnShellHeader<VertexIn, VertexOut> = {\n in: options.in,\n out: options.out,\n argTypes: options.in && Object.keys(options.in).length !== 0\n ? [createIoSchema(options.in)]\n : [],\n entryPoint: 'vertex',\n };\n\n const call = (\n arg: Implementation | TemplateStringsArray,\n ...values: unknown[]\n ) => createVertexFn(shell, stripTemplate(arg, ...values));\n\n return Object.assign(call, shell) as unknown as TgpuVertexFnShell<\n VertexIn,\n VertexOut\n >;\n}\n\nexport function isTgpuVertexFn<\n VertexIn extends VertexInConstrained,\n VertexOut extends VertexOutConstrained,\n>(\n value: unknown,\n): value is TgpuVertexFn<VertexIn, VertexOut> {\n return (value as TgpuVertexFn<VertexIn, VertexOut>)?.shell?.entryPoint ===\n 'vertex';\n}\n\n// --------------\n// Implementation\n// --------------\n\nfunction createVertexFn(\n shell: TgpuVertexFnShellHeader<VertexInConstrained, VertexOutConstrained>,\n implementation: Implementation,\n): TgpuVertexFn<VertexInConstrained, VertexOutConstrained> {\n type This =\n & TgpuVertexFn<VertexInConstrained, VertexOutConstrained>\n & SelfResolvable\n & {\n [$internal]: true;\n [$getNameForward]: FnCore;\n };\n\n const core = createFnCore(implementation, '@vertex ');\n const inputType = shell.argTypes[0];\n\n const result: This = {\n shell,\n\n $uses(newExternals) {\n core.applyExternals(newExternals);\n return this;\n },\n\n [$internal]: true,\n [$getNameForward]: core,\n $name(newLabel: string): This {\n setName(this, newLabel);\n if (isNamable(inputType)) {\n inputType.$name(`${newLabel}_Input`);\n }\n return this;\n },\n\n [$resolve](ctx: ResolutionCtx): ResolvedSnippet {\n const outputWithLocation = createIoSchema(\n shell.out,\n ctx.varyingLocations,\n ).$name(`${getName(this) ?? ''}_Output`);\n\n if (typeof implementation === 'string') {\n if (inputType) {\n core.applyExternals({ In: inputType });\n }\n core.applyExternals({ Out: outputWithLocation });\n }\n\n return ctx.withSlots([[shaderStageSlot, 'vertex']], () =>\n core.resolve(\n ctx,\n shell.argTypes,\n outputWithLocation,\n ));\n },\n\n toString() {\n return `vertexFn:${getName(core) ?? '<unnamed>'}`;\n },\n };\n return result;\n}\n","import { builtin } from '../builtin.ts';\nimport { vertexFn } from '../core/function/tgpuVertexFn.ts';\nimport { vec2f } from '../data/vector.ts';\n\n/**\n * A vertex function that defines a single full-screen triangle out\n * of three points.\n *\n * @example\n * ```ts\n * import { common } from 'typegpu';\n *\n * const pipeline = root.createRenderPipeline({\n * vertex: common.fullScreenTriangle,\n * fragment: yourFragmentShader,\n * });\n *\n * pipeline.draw(3);\n * ```\n */\nexport const fullScreenTriangle = vertexFn({\n in: { vertexIndex: builtin.vertexIndex },\n out: { pos: builtin.position, uv: vec2f },\n})`{\n const pos = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));\n const uv = array<vec2f, 3>(vec2f(0, 1), vec2f(2, 1), vec2f(0, -1));\n\n return Out(vec4f(pos[in.vertexIndex], 0, 1), uv[in.vertexIndex]);\n}`;\n"],"mappings":";;;;AAGA,SAAgB,YACd,QACS;AACT,QAAQ,SAAmC;;;;;ACoB7C,MAAM,wBAAwB;CAC5B,SAAS;CACT,SAAS;CACT,SAAS;CACV;AAED,SAAgB,YACd,QACA,UACqB;CACrB,MAAM,QAAQ,OAAO,aAAa,WAC9B,gBAAgB,SAAS,GACzB;AAGJ,KAAI,YAAY,OAAO,SAAS,IAAI,WAAW,OAAO,SAAS,EAAE;EAC/D,MAAM,cAAc,OAAO,SAAS;EACpC,MAAM,kBAAkB,qBAAqB,YAAY;EACzD,MAAM,oBAAoB,mBAAmB,OAAO;EACpD,MAAM,kBAAkB,MAAM,WAAW;EAEzC,IAAI;AAEJ,MAAI,OAAO,WAAW,0BAEpB,KAAI,gBACF,UAAS,kBAAkB,aAAa;MAExC,UAAS,kBAAkB,YAAY;WAEhC,OAAO,WAAW,yBAE3B,UAAS,kBAAkB,YAAY;WAC9B,CAAC,qBAAqB,CAAC,gBAEhC,UAAS,OAAO;WACP,mBA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