typegpu 0.12.7 → 0.12.9

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 (84) hide show
  1. package/core/function/autoIO.js +2 -2
  2. package/core/function/comptime.js +7 -5
  3. package/core/function/createCallableSchema.js +4 -3
  4. package/core/function/dualImpl.js +21 -19
  5. package/core/function/ioSchema.d.ts +10 -0
  6. package/core/function/ioSchema.js +37 -16
  7. package/core/function/tgpuFn.d.ts +12 -1
  8. package/core/function/tgpuFn.js +19 -2
  9. package/core/pipeline/computePipeline.js +5 -2
  10. package/core/pipeline/renderPipeline.d.ts +4 -2
  11. package/core/pipeline/renderPipeline.js +17 -12
  12. package/core/pipeline/timeable.js +15 -2
  13. package/core/pipeline/webgpuLimitations.js +9 -2
  14. package/core/root/configurableImpl.js +1 -2
  15. package/core/root/init.d.ts +3 -3
  16. package/core/root/init.js +12 -13
  17. package/core/root/rootTypes.d.ts +4 -1
  18. package/core/slot/accessor.js +3 -3
  19. package/core/texture/externalTexture.d.ts +1 -1
  20. package/core/texture/externalTexture.js +3 -1
  21. package/core/texture/texture.d.ts +3 -2
  22. package/core/texture/texture.js +27 -25
  23. package/core/unroll/tgpuUnroll.d.ts +4 -3
  24. package/core/unroll/tgpuUnroll.js +7 -1
  25. package/core/valueProxyUtils.d.ts +4 -2
  26. package/core/valueProxyUtils.js +4 -2
  27. package/data/compiledIO.js +13 -10
  28. package/data/dataIO.d.ts +10 -6
  29. package/data/dataIO.js +35 -20
  30. package/data/dataTypes.d.ts +0 -5
  31. package/data/dataTypes.js +0 -6
  32. package/data/index.d.ts +4 -3
  33. package/data/index.js +3 -2
  34. package/data/matrixColumnsAccess.d.ts +8 -0
  35. package/data/matrixColumnsAccess.js +15 -0
  36. package/data/offsetUtils.js +181 -102
  37. package/data/ref.d.ts +12 -5
  38. package/data/ref.js +50 -23
  39. package/data/schemasEqual.d.ts +37 -0
  40. package/data/schemasEqual.js +131 -0
  41. package/data/snippet.d.ts +7 -0
  42. package/data/snippet.js +9 -0
  43. package/data/struct.js +5 -0
  44. package/data/wgslTypes.d.ts +4 -4
  45. package/package.json +2 -2
  46. package/resolutionCtx.js +1 -1
  47. package/serial/restore.d.ts +3 -2
  48. package/serial/restore.js +2 -1
  49. package/shared/meta.js +1 -1
  50. package/shared/symbols.d.ts +5 -0
  51. package/shared/symbols.js +6 -1
  52. package/std/comptime.d.ts +67 -0
  53. package/std/comptime.js +90 -0
  54. package/std/index.d.ts +2 -0
  55. package/std/index.js +2 -0
  56. package/std/numeric.d.ts +1 -1
  57. package/std/numeric.js +13 -13
  58. package/std/packing.js +10 -10
  59. package/std/typeOf.d.ts +31 -0
  60. package/std/typeOf.js +56 -0
  61. package/tgpuLogger.d.ts +4 -1
  62. package/tgpuLogger.js +3 -2
  63. package/tgsl/accessIndex.js +18 -15
  64. package/tgsl/accessProp.js +10 -7
  65. package/tgsl/consoleLog/serializers.d.ts +1 -8
  66. package/tgsl/consoleLog/serializers.js +53 -37
  67. package/tgsl/conversion.js +3 -2
  68. package/tgsl/forOfUtils.js +2 -2
  69. package/tgsl/generationHelpers.d.ts +4 -3
  70. package/tgsl/generationHelpers.js +16 -3
  71. package/tgsl/infixDispatch.d.ts +4 -1
  72. package/tgsl/infixDispatch.js +13 -1
  73. package/tgsl/makeDereferenceable.d.ts +1 -1
  74. package/tgsl/makeDereferenceable.js +3 -1
  75. package/tgsl/shellless.js +8 -29
  76. package/tgsl/stringifySnippet.d.ts +9 -0
  77. package/tgsl/stringifySnippet.js +24 -0
  78. package/tgsl/wgslGenerator.d.ts +1 -0
  79. package/tgsl/wgslGenerator.js +98 -66
  80. package/types.d.ts +23 -2
  81. package/types.js +30 -5
  82. package/unwrapper.d.ts +2 -2
  83. package/data/deepEqual.d.ts +0 -21
  84. package/data/deepEqual.js +0 -93
@@ -0,0 +1,31 @@
1
+ import type { AnyData } from '../data/dataTypes.ts';
2
+ import type { GPUCallable } from '../types.ts';
3
+ interface TypeOf extends GPUCallable {
4
+ (arg: unknown): AnyData | undefined;
5
+ }
6
+ /**
7
+ * Returns the type of an expression, the one it will have during shader execution. That information can
8
+ * be used to introspect or specialize the shader. It will return `undefined` if the expression cannot
9
+ * be represented in shader code, or if the type is unknown at the point where the query is made.
10
+ *
11
+ * The returned value is only known at shader-generation time and has no WGSL representation, so it
12
+ * cannot be stored in a variable (e.g. `const t = std.typeOf(a)` throws). Consume it immediately,
13
+ * e.g. by comparing it (`std.typeOf(a) === d.f32`) or passing it to a comptime function.
14
+ *
15
+ * @example
16
+ * function double(value: number) {
17
+ * 'use gpu';
18
+ * if (std.typeOf(value) === d.f32) {
19
+ * return value * 2;
20
+ * }
21
+ * return value << 1;
22
+ * }
23
+ *
24
+ * function main() {
25
+ * 'use gpu';
26
+ * double(1.5); // generates double(f32), which multiplies by 2
27
+ * double(1); // generates double(i32), which shifts left by 1
28
+ * }
29
+ */
30
+ export declare const typeOf: TypeOf;
31
+ export {};
package/std/typeOf.js ADDED
@@ -0,0 +1,56 @@
1
+ import { isWgslData } from "../data/wgslTypes.js";
2
+ import { setName } from "../shared/meta.js";
3
+ import { $gpuCallable, $internal } from "../shared/symbols.js";
4
+ import { coerceToSnippet } from "../tgsl/generationHelpers.js";
5
+ /**
6
+ * Returns the type of an expression, the one it will have during shader execution. That information can
7
+ * be used to introspect or specialize the shader. It will return `undefined` if the expression cannot
8
+ * be represented in shader code, or if the type is unknown at the point where the query is made.
9
+ *
10
+ * The returned value is only known at shader-generation time and has no WGSL representation, so it
11
+ * cannot be stored in a variable (e.g. `const t = std.typeOf(a)` throws). Consume it immediately,
12
+ * e.g. by comparing it (`std.typeOf(a) === d.f32`) or passing it to a comptime function.
13
+ *
14
+ * @example
15
+ * function double(value: number) {
16
+ * 'use gpu';
17
+ * if (std.typeOf(value) === d.f32) {
18
+ * return value * 2;
19
+ * }
20
+ * return value << 1;
21
+ * }
22
+ *
23
+ * function main() {
24
+ * 'use gpu';
25
+ * double(1.5); // generates double(f32), which multiplies by 2
26
+ * double(1); // generates double(i32), which shifts left by 1
27
+ * }
28
+ */
29
+ export const typeOf = (() => {
30
+ const impl = (() => {
31
+ // Deducing the WGSL type of a value at comptime is near-impossible with
32
+ // the current comptime type flowing. We can lift this restriction once it
33
+ // becomes more capable.
34
+ throw new Error('std.typeOf() cannot be called in JS, it can only be used in the GPU context. You can use std.isBeingTranspiled() to branch off and provide a fallback.');
35
+ });
36
+ setName(impl, 'typeOf');
37
+ impl.toString = () => 'typeOf';
38
+ impl[$gpuCallable] = {
39
+ call(_ctx, args) {
40
+ const [arg] = args;
41
+ if (!arg || args.length > 1) {
42
+ throw new Error(`std.typeOf() expects exactly one argument, got ${args.length}`);
43
+ }
44
+ const type = arg.dataType;
45
+ // Only public data types are exposed. Unknown types and internal types
46
+ // (e.g. AutoStruct, EntryInputRouter) must not leak to the user.
47
+ if (!isWgslData(type)) {
48
+ return coerceToSnippet(undefined);
49
+ }
50
+ return coerceToSnippet(type);
51
+ },
52
+ };
53
+ // Mark as internal
54
+ Object.defineProperty(impl, $internal, { value: true });
55
+ return impl;
56
+ })();
package/tgpuLogger.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- declare const warningTypes: readonly ["deprecated", "suspicious", "fallback", "precision-loss", "implicit-conversion", "webgpu-feature-missing", "webgpu-limits-exceeded", "locations-mismatched", "log-limit-exceeded", "external-omitted", "uniform-schema-misaligned"];
1
+ declare const warningTypes: readonly ["deprecated", "suspicious", "fallback", "precision-loss", "implicit-conversion", "webgpu-feature-missing", "webgpu-limits-exceeded", "log-limit-exceeded", "external-omitted", "uniform-schema-misaligned"];
2
2
  type WarningType = (typeof warningTypes)[number];
3
3
  interface Logger {
4
+ /** Lets callers skip computing what a warning needs when it wouldn't be shown anyway. */
5
+ isEnabled(type: WarningType): boolean;
4
6
  warn(type: WarningType, ...args: unknown[]): void;
5
7
  warnOnce(type: WarningType, key: object, tag: string, ...args: unknown[]): void;
6
8
  }
@@ -26,6 +28,7 @@ export declare class TgpuLogger implements Logger, Warn {
26
28
  constructor(prod: boolean);
27
29
  disable(type: WarningType): void;
28
30
  reset(): void;
31
+ isEnabled(type: WarningType): boolean;
29
32
  warn(type: WarningType, ...args: unknown[]): void;
30
33
  warnOnce(type: WarningType, key: object, tag: string, ...args: unknown[]): void;
31
34
  }
package/tgpuLogger.js CHANGED
@@ -7,7 +7,6 @@ const warningTypes = [
7
7
  'implicit-conversion',
8
8
  'webgpu-feature-missing',
9
9
  'webgpu-limits-exceeded',
10
- 'locations-mismatched',
11
10
  'log-limit-exceeded',
12
11
  'external-omitted',
13
12
  'uniform-schema-misaligned',
@@ -21,7 +20,6 @@ export class TgpuLogger {
21
20
  this.#initialEnabledWarnings = [
22
21
  'webgpu-feature-missing',
23
22
  'webgpu-limits-exceeded',
24
- 'locations-mismatched',
25
23
  'log-limit-exceeded',
26
24
  'external-omitted',
27
25
  ];
@@ -37,6 +35,9 @@ export class TgpuLogger {
37
35
  reset() {
38
36
  this.#enabledWarnings = new Set(this.#initialEnabledWarnings);
39
37
  }
38
+ isEnabled(type) {
39
+ return this.#enabledWarnings.has(type);
40
+ }
40
41
  warn(type, ...args) {
41
42
  if (this.#enabledWarnings.has(type)) {
42
43
  console.warn(`⚠️ [${type}] `, ...args);
@@ -1,10 +1,11 @@
1
1
  import { stitch } from "../core/resolve/stitch.js";
2
- import { isDisarray, MatrixColumnsAccess } from "../data/dataTypes.js";
2
+ import { isDisarray } from "../data/dataTypes.js";
3
+ import { MatrixColumnsAccess } from "../data/matrixColumnsAccess.js";
3
4
  import { derefSnippet } from "../data/ref.js";
4
5
  import { snip } from "../data/snippet.js";
5
6
  import { vec2f, vec3f, vec4f } from "../data/vector.js";
6
- import { isPtr, isVec, isWgslArray, isWgslStruct } from "../data/wgslTypes.js";
7
- import { isKnownAtComptime } from "../types.js";
7
+ import { isPtr, isVec, isWgslArray } from "../data/wgslTypes.js";
8
+ import { asComptime } from "../types.js";
8
9
  import { accessProp } from "./accessProp.js";
9
10
  import { ArrayExpression, coerceToSnippet } from "./generationHelpers.js";
10
11
  const indexableTypeToResult = {
@@ -30,24 +31,27 @@ function deriveIndexAccessOrigin(targetOrigin, indexOrigin) {
30
31
  }
31
32
  export function accessIndex(target, indexArg) {
32
33
  const index = typeof indexArg === 'number' ? coerceToSnippet(indexArg) : indexArg;
34
+ const knownIndex = asComptime(index);
33
35
  // array
34
36
  if (isWgslArray(target.dataType) || isDisarray(target.dataType)) {
35
37
  const elementType = target.dataType.elementType;
36
- if (target.value instanceof ArrayExpression && isKnownAtComptime(index)) {
37
- return target.value.elements[index.value];
38
+ if (target.value instanceof ArrayExpression && knownIndex) {
39
+ return target.value.elements[knownIndex.value];
38
40
  }
39
41
  const origin = deriveIndexAccessOrigin(target.origin, index.origin);
40
- return snip(isKnownAtComptime(target) && isKnownAtComptime(index)
42
+ const knownTarget = knownIndex && asComptime(target);
43
+ return snip(knownTarget && knownIndex
41
44
  ? // oxlint-disable-next-line typescript/no-explicit-any -- it's fine, it's there
42
- target.value[index.value]
45
+ knownTarget.value[knownIndex.value]
43
46
  : stitch `${target}[${index}]`, elementType,
44
47
  /* origin */ origin, target.possibleSideEffects || index.possibleSideEffects);
45
48
  }
46
49
  // vector
47
50
  if (isVec(target.dataType)) {
48
- return snip(isKnownAtComptime(target) && isKnownAtComptime(index)
51
+ const knownTarget = knownIndex && asComptime(target);
52
+ return snip(knownTarget && knownIndex
49
53
  ? // oxlint-disable-next-line typescript/no-explicit-any -- it's fine, it's there
50
- target.value[index.value]
54
+ knownTarget.value[knownIndex.value]
51
55
  : stitch `${target}[${index}]`, target.dataType.primitive, deriveIndexAccessOrigin(target.origin, index.origin), target.possibleSideEffects || index.possibleSideEffects);
52
56
  }
53
57
  if (isPtr(target.dataType)) {
@@ -64,16 +68,15 @@ export function accessIndex(target, indexArg) {
64
68
  if (target.dataType.type in indexableTypeToResult) {
65
69
  throw new Error("The only way of accessing matrix elements in TypeGPU functions is through the 'columns' property.");
66
70
  }
67
- if (isKnownAtComptime(target) && isKnownAtComptime(index)) {
71
+ const knownTarget = knownIndex && asComptime(target);
72
+ if (knownTarget && knownIndex) {
68
73
  // No idea what the type is, so we act on the snippet's value and try to guess
69
74
  return coerceToSnippet(
70
75
  // oxlint-disable-next-line typescript/no-explicit-any -- we're inspecting the value, and it could be any value
71
- target.value[index.value]);
76
+ knownTarget.value[knownIndex.value]);
72
77
  }
73
- if (isWgslStruct(target.dataType) &&
74
- isKnownAtComptime(index) &&
75
- typeof index.value === 'string') {
76
- return accessProp(target, index.value);
78
+ if (typeof knownIndex?.value === 'string') {
79
+ return accessProp(target, knownIndex.value);
77
80
  }
78
81
  return undefined;
79
82
  }
@@ -1,13 +1,14 @@
1
1
  import { stitch } from "../core/resolve/stitch.js";
2
2
  import { AutoStruct } from "../data/autoStruct.js";
3
3
  import { EntryInputRouter } from "../core/function/entryInputRouter.js";
4
- import { isUnstruct, MatrixColumnsAccess, UnknownData } from "../data/dataTypes.js";
4
+ import { isUnstruct, UnknownData } from "../data/dataTypes.js";
5
+ import { MatrixColumnsAccess } from "../data/matrixColumnsAccess.js";
5
6
  import { bool, f16, f32, i32, u32 } from "../data/numeric.js";
6
7
  import { derefSnippet } from "../data/ref.js";
7
8
  import { isSnippet, snip } from "../data/snippet.js";
8
9
  import { vec2b, vec2f, vec2h, vec2i, vec2u, vec3b, vec3f, vec3h, vec3i, vec3u, vec4b, vec4f, vec4h, vec4i, vec4u, } from "../data/vector.js";
9
10
  import { isMat, isPtr, isVec, isWgslArray, isWgslStruct, } from "../data/wgslTypes.js";
10
- import { isKnownAtComptime } from "../types.js";
11
+ import { asComptime } from "../types.js";
11
12
  import { coerceToSnippet, numericLiteralToSnippet } from "./generationHelpers.js";
12
13
  import { InfixDispatch, infixOperators } from "./infixDispatch.js";
13
14
  import { accessStructProp } from "./accessStructProp.js";
@@ -128,9 +129,10 @@ export function accessProp(target, propName) {
128
129
  if (!swizzleType) {
129
130
  return undefined;
130
131
  }
131
- return snip(isKnownAtComptime(target)
132
+ const knownTarget = asComptime(target);
133
+ return snip(knownTarget
132
134
  ? // oxlint-disable-next-line typescript/no-explicit-any -- it's fine, the prop is there
133
- target.value[propName]
135
+ knownTarget.value[propName]
134
136
  : stitch `${target}.${propName}`, swizzleType,
135
137
  // Swizzling creates new vectors (unless they're on the lhs of an assignment, but that's not yet supported in WGSL)
136
138
  /* origin */ propLength === 1
@@ -139,9 +141,10 @@ export function accessProp(target, propName) {
139
141
  ? 'constant'
140
142
  : 'runtime', target.possibleSideEffects);
141
143
  }
142
- if (isKnownAtComptime(target) || target.dataType === UnknownData) {
143
- // oxlint-disable-next-line typescript/no-explicit-any -- we either know exactly what it is, or have no idea at all
144
- const prop = target.value[propName];
144
+ const knownTarget = asComptime(target);
145
+ if (knownTarget) {
146
+ // oxlint-disable-next-line typescript/no-explicit-any
147
+ const prop = knownTarget.value[propName];
145
148
  if (isNamable(prop) && getName(prop) === undefined) {
146
149
  setName(prop, propName);
147
150
  }
@@ -1,13 +1,7 @@
1
1
  import type { TgpuMutable } from '../../core/buffer/bufferBinding.ts';
2
2
  import { type TgpuFn } from '../../core/function/tgpuFn.ts';
3
- import { type AnyWgslData, type Atomic, type U32, type Void, type WgslArray } from '../../data/wgslTypes.ts';
3
+ import { type AnyWgslData, type Atomic, type U32, type WgslArray } from '../../data/wgslTypes.ts';
4
4
  import type { LogGeneratorOptions, SerializedLogCallData } from './types.ts';
5
- type SerializerMap = {
6
- [K in AnyWgslData['type']]?: TgpuFn<(args_0: Extract<AnyWgslData, {
7
- type: K;
8
- }>) => Void>;
9
- };
10
- export declare const serializerMap: SerializerMap;
11
5
  /**
12
6
  * Creates a TGPU function that serializes data to the log buffer.
13
7
  *
@@ -18,4 +12,3 @@ export declare const serializerMap: SerializerMap;
18
12
  * @param logOptions - Configuration options
19
13
  */
20
14
  export declare function createLoggingFunction(id: number, dataTypes: AnyWgslData[], dataBuffer: TgpuMutable<WgslArray<SerializedLogCallData>>, indexBuffer: TgpuMutable<Atomic<U32>>, logOptions: Required<LogGeneratorOptions>): TgpuFn;
21
- export {};
@@ -7,111 +7,116 @@ import { sizeOf } from "../../data/sizeOf.js";
7
7
  import { vec2b, vec2f, vec2h, vec2i, vec2u, vec3b, vec3f, vec3h, vec3i, vec3u, vec4b, vec4f, vec4h, vec4i, vec4u, } from "../../data/vector.js";
8
8
  import { isWgslArray, isWgslStruct, } from "../../data/wgslTypes.js";
9
9
  import { getName } from "../../shared/meta.js";
10
- const dataBlockIndex = privateVar(u32, 0).$name('dataBlockIndex');
11
- const dataByteIndex = privateVar(u32, 0).$name('dataByteIndex');
12
- const dataBufferSlot = slot().$name('dataBuffer');
13
- const nextByteIndex = fn([], u32) `() {
10
+ /**
11
+ * The serializers are only needed when shaders log something, so they're created on first use
12
+ * instead of on import (creating them is not free, and most apps never log from shaders).
13
+ */
14
+ function createSerializerState() {
15
+ const dataBlockIndex = privateVar(u32, 0).$name('dataBlockIndex');
16
+ const dataByteIndex = privateVar(u32, 0).$name('dataByteIndex');
17
+ const dataBufferSlot = slot().$name('dataBuffer');
18
+ const nextByteIndex = fn([], u32) `() {
14
19
  let i = dataByteIndex;
15
20
  dataByteIndex = dataByteIndex + 1u;
16
21
  return i;
17
22
  }`
18
- .$uses({ dataByteIndex })
19
- .$name('nextByteIndex');
20
- const nextU32 = 'dataBuffer[dataBlockIndex].serializedData[nextByteIndex()]';
21
- export const serializerMap = {
22
- f32: fn([f32]) `(n) {
23
+ .$uses({ dataByteIndex })
24
+ .$name('nextByteIndex');
25
+ const nextU32 = 'dataBuffer[dataBlockIndex].serializedData[nextByteIndex()]';
26
+ const serializerMap = {
27
+ f32: fn([f32]) `(n) {
23
28
  ${nextU32} = bitcast<u32>(n);
24
29
  }`,
25
- f16: fn([f16]) `(n) {
30
+ f16: fn([f16]) `(n) {
26
31
  ${nextU32} = pack2x16float(vec2f(f32(n), 0.0));
27
32
  }`,
28
- i32: fn([i32]) `(n) {
33
+ i32: fn([i32]) `(n) {
29
34
  ${nextU32} = bitcast<u32>(n);
30
35
  }`,
31
- u32: fn([u32]) `(n) {
36
+ u32: fn([u32]) `(n) {
32
37
  ${nextU32} = n;
33
38
  }`,
34
- bool: fn([bool]) `(b) {
39
+ bool: fn([bool]) `(b) {
35
40
  ${nextU32} = u32(b);
36
41
  }`,
37
- vec2f: fn([vec2f]) `(v) {
42
+ vec2f: fn([vec2f]) `(v) {
38
43
  ${nextU32} = bitcast<u32>(v.x);
39
44
  ${nextU32} = bitcast<u32>(v.y);
40
45
  }`,
41
- vec3f: fn([vec3f]) `(v) {
46
+ vec3f: fn([vec3f]) `(v) {
42
47
  ${nextU32} = bitcast<u32>(v.x);
43
48
  ${nextU32} = bitcast<u32>(v.y);
44
49
  ${nextU32} = bitcast<u32>(v.z);
45
50
  }`,
46
- vec4f: fn([vec4f]) `(v) {
51
+ vec4f: fn([vec4f]) `(v) {
47
52
  ${nextU32} = bitcast<u32>(v.x);
48
53
  ${nextU32} = bitcast<u32>(v.y);
49
54
  ${nextU32} = bitcast<u32>(v.z);
50
55
  ${nextU32} = bitcast<u32>(v.w);
51
56
  }`,
52
- vec2h: fn([vec2h]) `(v) {
57
+ vec2h: fn([vec2h]) `(v) {
53
58
  ${nextU32} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
54
59
  }`,
55
- vec3h: fn([vec3h]) `(v) {
60
+ vec3h: fn([vec3h]) `(v) {
56
61
  ${nextU32} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
57
62
  ${nextU32} = pack2x16float(vec2f(f32(v.z), 0.0));
58
63
  }`,
59
- vec4h: fn([vec4h]) `(v) {
64
+ vec4h: fn([vec4h]) `(v) {
60
65
  ${nextU32} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
61
66
  ${nextU32} = pack2x16float(vec2f(f32(v.z), f32(v.w)));
62
67
  }`,
63
- vec2i: fn([vec2i]) `(v) {
68
+ vec2i: fn([vec2i]) `(v) {
64
69
  ${nextU32} = bitcast<u32>(v.x);
65
70
  ${nextU32} = bitcast<u32>(v.y);
66
71
  }`,
67
- vec3i: fn([vec3i]) `(v) {
72
+ vec3i: fn([vec3i]) `(v) {
68
73
  ${nextU32} = bitcast<u32>(v.x);
69
74
  ${nextU32} = bitcast<u32>(v.y);
70
75
  ${nextU32} = bitcast<u32>(v.z);
71
76
  }`,
72
- vec4i: fn([vec4i]) `(v) {
77
+ vec4i: fn([vec4i]) `(v) {
73
78
  ${nextU32} = bitcast<u32>(v.x);
74
79
  ${nextU32} = bitcast<u32>(v.y);
75
80
  ${nextU32} = bitcast<u32>(v.z);
76
81
  ${nextU32} = bitcast<u32>(v.w);
77
82
  }`,
78
- vec2u: fn([vec2u]) `(v) {
83
+ vec2u: fn([vec2u]) `(v) {
79
84
  ${nextU32} = v.x;
80
85
  ${nextU32} = v.y;
81
86
  }`,
82
- vec3u: fn([vec3u]) `(v) {
87
+ vec3u: fn([vec3u]) `(v) {
83
88
  ${nextU32} = v.x;
84
89
  ${nextU32} = v.y;
85
90
  ${nextU32} = v.z;
86
91
  }`,
87
- vec4u: fn([vec4u]) `(v) {
92
+ vec4u: fn([vec4u]) `(v) {
88
93
  ${nextU32} = v.x;
89
94
  ${nextU32} = v.y;
90
95
  ${nextU32} = v.z;
91
96
  ${nextU32} = v.w;
92
97
  }`,
93
- 'vec2<bool>': fn([vec2b]) `(v) {
98
+ 'vec2<bool>': fn([vec2b]) `(v) {
94
99
  ${nextU32} = u32(v.x);
95
100
  ${nextU32} = u32(v.y);
96
101
  }`,
97
- 'vec3<bool>': fn([vec3b]) `(v) {
102
+ 'vec3<bool>': fn([vec3b]) `(v) {
98
103
  ${nextU32} = u32(v.x);
99
104
  ${nextU32} = u32(v.y);
100
105
  ${nextU32} = u32(v.z);
101
106
  }`,
102
- 'vec4<bool>': fn([vec4b]) `(v) {
107
+ 'vec4<bool>': fn([vec4b]) `(v) {
103
108
  ${nextU32} = u32(v.x);
104
109
  ${nextU32} = u32(v.y);
105
110
  ${nextU32} = u32(v.z);
106
111
  ${nextU32} = u32(v.w);
107
112
  }`,
108
- mat2x2f: fn([mat2x2f]) `(m) {
113
+ mat2x2f: fn([mat2x2f]) `(m) {
109
114
  ${nextU32} = bitcast<u32>(m[0][0]);
110
115
  ${nextU32} = bitcast<u32>(m[0][1]);
111
116
  ${nextU32} = bitcast<u32>(m[1][0]);
112
117
  ${nextU32} = bitcast<u32>(m[1][1]);
113
118
  }`,
114
- mat3x3f: fn([mat3x3f]) `(m) {
119
+ mat3x3f: fn([mat3x3f]) `(m) {
115
120
  ${nextU32} = bitcast<u32>(m[0][0]);
116
121
  ${nextU32} = bitcast<u32>(m[0][1]);
117
122
  ${nextU32} = bitcast<u32>(m[0][2]);
@@ -125,7 +130,7 @@ export const serializerMap = {
125
130
  ${nextU32} = bitcast<u32>(m[2][2]);
126
131
  ${nextU32} = 0u;
127
132
  }`,
128
- mat4x4f: fn([mat4x4f]) `(m) {
133
+ mat4x4f: fn([mat4x4f]) `(m) {
129
134
  ${nextU32} = bitcast<u32>(m[0][0]);
130
135
  ${nextU32} = bitcast<u32>(m[0][1]);
131
136
  ${nextU32} = bitcast<u32>(m[0][2]);
@@ -143,12 +148,21 @@ export const serializerMap = {
143
148
  ${nextU32} = bitcast<u32>(m[3][2]);
144
149
  ${nextU32} = bitcast<u32>(m[3][3]);
145
150
  }`,
146
- };
147
- // rename the functions and add externals
148
- for (const [name, serializer] of Object.entries(serializerMap)) {
149
- serializer
150
- .$name(`serialize${name[0].toLocaleUpperCase()}${name.slice(1)}`)
151
- .$uses({ dataBlockIndex, nextByteIndex, dataBuffer: dataBufferSlot });
151
+ };
152
+ // rename the functions and add externals
153
+ for (const [name, serializer] of Object.entries(serializerMap)) {
154
+ serializer
155
+ .$name(`serialize${name[0].toLocaleUpperCase()}${name.slice(1)}`)
156
+ .$uses({ dataBlockIndex, nextByteIndex, dataBuffer: dataBufferSlot });
157
+ }
158
+ return { dataBlockIndex, dataByteIndex, dataBufferSlot, serializerMap };
159
+ }
160
+ let serializerState;
161
+ function getSerializerState() {
162
+ if (!serializerState) {
163
+ serializerState = createSerializerState();
164
+ }
165
+ return serializerState;
152
166
  }
153
167
  // -------
154
168
  // Helpers
@@ -165,6 +179,7 @@ function generateHeader(argTypes) {
165
179
  * @param dataBuffer - A buffer to store serialized log call data (a necessary external for the returned function)
166
180
  */
167
181
  function getSerializer(dataType, dataBuffer) {
182
+ const { serializerMap, dataBufferSlot } = getSerializerState();
168
183
  const maybeSerializer = serializerMap[dataType.type];
169
184
  if (maybeSerializer) {
170
185
  return maybeSerializer.with(dataBufferSlot, dataBuffer);
@@ -221,6 +236,7 @@ export function createLoggingFunction(id, dataTypes, dataBuffer, indexBuffer, lo
221
236
  if (serializedSize > logOptions.logSizeLimit) {
222
237
  throw new Error(`Logged data needs to fit in ${logOptions.logSizeLimit} bytes (one of the logs requires ${serializedSize} bytes). Consider increasing the limit by passing appropriate options to tgpu.init().`);
223
238
  }
239
+ const { dataBlockIndex, dataByteIndex } = getSerializerState();
224
240
  const compoundSerializer = createCompoundSerializer(dataTypes, dataBuffer).$name(`log${id}serializer`);
225
241
  const header = generateHeader(dataTypes);
226
242
  return fn(dataTypes) `${header} {
@@ -10,6 +10,7 @@ import { safeStringify } from "../shared/stringify.js";
10
10
  import { assertExhaustive } from "../shared/utilityTypes.js";
11
11
  import { logger } from "../tgpuLogger.js";
12
12
  import { accessStructProp } from "./accessStructProp.js";
13
+ import { stringifySnippet } from "./stringifySnippet.js";
13
14
  const INFINITE_RANK = {
14
15
  rank: Number.POSITIVE_INFINITY,
15
16
  action: 'none',
@@ -254,7 +255,7 @@ export function convertToCommonType(ctx, values, restrictTo, verbose = true) {
254
255
  }
255
256
  if (verbose && conversion.hasImplicitConversions) {
256
257
  logger.warn('implicit-conversion', `Implicit conversions from [\n${values
257
- .map((v) => ` ${ctx.resolveSnippet(v).value}: ${safeStringify(v.dataType)}`)
258
+ .map((v) => ` ${stringifySnippet(v)}: ${safeStringify(v.dataType)}`)
258
259
  .join(',\n')}\n] to ${conversion.targetType.type} are supported, but not recommended.
259
260
  Consider using explicit conversions instead.`);
260
261
  }
@@ -281,7 +282,7 @@ export function tryConvertSnippet(ctx, snippet, targetDataTypes, verbose = true)
281
282
  if (converted) {
282
283
  return converted[0];
283
284
  }
284
- throw new WgslTypeError(`Cannot convert value of type '${String(dataType)}' to any of the target types: [${targets.map((t) => t.type).join(', ')}]`);
285
+ throw new WgslTypeError(`Cannot convert '${stringifySnippet(snippet)}' of type '${String(dataType)}' to any of the target types: [${targets.map((t) => t.type).join(', ')}]`);
285
286
  }
286
287
  export function convertStructValues(ctx, structType, values) {
287
288
  return Object.entries(structType.propTypes).map(([key, targetType]) => {
@@ -1,6 +1,5 @@
1
1
  import { UnknownData } from "../data/dataTypes.js";
2
2
  import { isAddressableOrigin, isStoredInMemory, snip } from "../data/snippet.js";
3
- import { stitch } from "../core/resolve/stitch.js";
4
3
  import * as wgsl from "../data/wgslTypes.js";
5
4
  import { i32, u32 } from "../data/numeric.js";
6
5
  import { invariant, WgslTypeError } from "../errors.js";
@@ -9,6 +8,7 @@ import { accessIndex } from "./accessIndex.js";
9
8
  import { createPtrFromOrigin, implicitFrom } from "../data/ptr.js";
10
9
  import { $gpuCallable } from "../shared/symbols.js";
11
10
  import { ArrayExpression, concretize } from "./generationHelpers.js";
11
+ import { stringifySnippet } from "./stringifySnippet.js";
12
12
  import { isTgpuRange } from "../std/range.js";
13
13
  export function getLoopVarKind(elementSnippet) {
14
14
  // If it's ephemeral, it's a value that cannot change. If it's a reference, we take
@@ -28,7 +28,7 @@ export function getElementSnippet(iterableSnippet, index) {
28
28
  export function getElementType(elementSnippet, iterableSnippet) {
29
29
  let elementType = elementSnippet.dataType;
30
30
  if (elementType === UnknownData) {
31
- throw new WgslTypeError(stitch `The elements in iterable ${iterableSnippet} are of unknown type`);
31
+ throw new WgslTypeError(`The elements in iterable '${stringifySnippet(iterableSnippet)}' are of unknown type`);
32
32
  }
33
33
  if (wgsl.isNaturallyEphemeral(elementSnippet.dataType) ||
34
34
  !isAddressableOrigin(elementSnippet.origin)) {
@@ -1,7 +1,7 @@
1
1
  import type { ResolvedSnippet, Snippet } from '../data/snippet.ts';
2
2
  import { type AnyWgslData, type BaseData, type F32, type I32, type WgslArray } from '../data/wgslTypes.ts';
3
- import { type ResolutionCtx, type SelfResolvable } from '../types.ts';
4
- import { $internal, $resolve } from '../shared/symbols.ts';
3
+ import { type ComptimeValue, type ResolutionCtx, type SelfResolvable, type WithComptimeValue } from '../types.ts';
4
+ import { $comptimeValueOf, $internal, $resolve } from '../shared/symbols.ts';
5
5
  export declare function numericLiteralToSnippet(value: number): Snippet;
6
6
  export declare function concretize<T extends BaseData>(type: T): T | F32 | I32;
7
7
  export declare function concretizeSnippet(snippet: Snippet): Snippet;
@@ -12,11 +12,12 @@ export declare function coerceToSnippet(value: unknown): Snippet;
12
12
  * Defers resolution. Stores array elements as snippets so the
13
13
  * generator can access them when needed.
14
14
  */
15
- export declare class ArrayExpression implements SelfResolvable {
15
+ export declare class ArrayExpression implements SelfResolvable, WithComptimeValue {
16
16
  readonly [$internal] = true;
17
17
  readonly type: WgslArray<AnyWgslData>;
18
18
  readonly elements: Snippet[];
19
19
  constructor(type: WgslArray<AnyWgslData>, elements: Snippet[]);
20
20
  toString(): string;
21
+ [$comptimeValueOf](): ComptimeValue;
21
22
  [$resolve](ctx: ResolutionCtx): ResolvedSnippet;
22
23
  }
@@ -3,10 +3,11 @@ import { abstractFloat, abstractInt, bool, f32, i32 } from "../data/numeric.js";
3
3
  import { isRef } from "../data/ref.js";
4
4
  import { isStoredInMemory, isSnippet, snip, withDataType } from "../data/snippet.js";
5
5
  import { isMatInstance, isNaturallyEphemeral, isVecInstance, WORKAROUND_getSchema, } from "../data/wgslTypes.js";
6
- import { getOwnSnippet } from "../types.js";
6
+ import { asComptime, getOwnSnippet, } from "../types.js";
7
7
  import { WgslTypeError } from "../errors.js";
8
- import { $internal, $resolve } from "../shared/symbols.js";
8
+ import { $comptimeValueOf, $internal, $resolve } from "../shared/symbols.js";
9
9
  import { logger } from "../tgpuLogger.js";
10
+ import { stringifySnippet } from "./stringifySnippet.js";
10
11
  export function numericLiteralToSnippet(value) {
11
12
  if (value >= 2 ** 63 || value < -(2 ** 63)) {
12
13
  return snip(value, abstractFloat, /* origin */ 'constant', /* possibleSideEffects */ false);
@@ -78,11 +79,23 @@ export class ArrayExpression {
78
79
  toString() {
79
80
  return 'ArrayExpression';
80
81
  }
82
+ [$comptimeValueOf]() {
83
+ // The array is known at comptime only if every element is known at comptime
84
+ const values = [];
85
+ for (const elem of this.elements) {
86
+ const known = asComptime(elem);
87
+ if (!known) {
88
+ return { comptime: false };
89
+ }
90
+ values.push(known.value);
91
+ }
92
+ return { comptime: true, value: values };
93
+ }
81
94
  [$resolve](ctx) {
82
95
  for (const elem of this.elements) {
83
96
  // We check if there are no references among the elements
84
97
  if (isStoredInMemory(elem) && !isNaturallyEphemeral(elem.dataType)) {
85
- const snippetStr = ctx.resolveSnippet(elem).value;
98
+ const snippetStr = stringifySnippet(elem);
86
99
  const snippetType = ctx.resolve(concretize(elem.dataType)).value;
87
100
  throw new WgslTypeError(`'${snippetStr}' reference cannot be used in an array constructor.\n-----\nTry '${snippetType}(${snippetStr})' or 'arrayOf(${snippetType}, count)([...])' to copy the value instead.\n-----`);
88
101
  }
@@ -2,6 +2,8 @@ import type { MatBase } from '../data/matrix.ts';
2
2
  import { type Snippet } from '../data/snippet.ts';
3
3
  import type { VecBase } from '../data/vectorImpl.ts';
4
4
  import type { AnyMatInstance, AnyNumericVecInstance } from '../data/wgslTypes.ts';
5
+ import { $comptimeValueOf } from '../shared/symbols.ts';
6
+ import { type ComptimeValue, type WithComptimeValue } from '../types.ts';
5
7
  export declare const infixOperators: {
6
8
  readonly add: import("../types.ts").DualFn<{
7
9
  (lhs: number, rhs: number): number;
@@ -56,10 +58,11 @@ export type InfixOperator = (typeof infixOperators)[InfixOperatorName];
56
58
  * d.vec2u(1).mul(2) // lhs is a snippet
57
59
  * }
58
60
  */
59
- export declare class InfixDispatch {
61
+ export declare class InfixDispatch implements WithComptimeValue {
60
62
  readonly lhs: Snippet | Numeric;
61
63
  readonly operator: InfixOperator;
62
64
  constructor(lhs: Snippet | Numeric, operator: InfixOperator);
65
+ [$comptimeValueOf](): ComptimeValue;
63
66
  }
64
67
  export declare function isInfixDispatch(o: unknown): o is InfixDispatch;
65
68
  /**
@@ -1,5 +1,7 @@
1
- import {} from "../data/snippet.js";
1
+ import { isSnippet } from "../data/snippet.js";
2
2
  import { inCodegenMode } from "../execMode.js";
3
+ import { $comptimeValueOf } from "../shared/symbols.js";
4
+ import { asComptime } from "../types.js";
3
5
  import { add, bitShiftLeft, bitShiftRight, div, mod, mul, sub } from "../std/operators.js";
4
6
  export const infixOperators = {
5
7
  add,
@@ -28,6 +30,16 @@ export class InfixDispatch {
28
30
  this.lhs = lhs;
29
31
  this.operator = operator;
30
32
  }
33
+ [$comptimeValueOf]() {
34
+ const known = isSnippet(this.lhs) ? asComptime(this.lhs) : { value: this.lhs };
35
+ if (!known) {
36
+ return { comptime: false };
37
+ }
38
+ // Same as accessing e.g. `.mul` on a vector in JS, but bound to `lhs`
39
+ const lhs = known.value;
40
+ const operator = this.operator;
41
+ return { comptime: true, value: (rhs) => operator(lhs, rhs) };
42
+ }
31
43
  }
32
44
  export function isInfixDispatch(o) {
33
45
  return o instanceof InfixDispatch;
@@ -1,5 +1,5 @@
1
1
  import type { Snippet } from '../data/snippet.ts';
2
- import type { SimulationState } from '../types.ts';
2
+ import { type SimulationState } from '../types.ts';
3
3
  import type { makeResolvable } from './makeResolvable.ts';
4
4
  /**
5
5
  * WARNING: This is an API that touches a lot of internals, and is not stable