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
@@ -67,9 +67,9 @@ export class AutoVertexFn {
67
67
  setName(impl, 'vertexFn');
68
68
  }
69
69
  this.#core = createFnCore(impl, 'vertex');
70
- this.autoIn = new AutoStruct({ ...builtinVertexIn, ...attribs }, undefined, locations);
70
+ this.autoIn = new AutoStruct({ ...builtinVertexIn, ...attribs }, undefined);
71
71
  setName(this.autoIn, 'VertexIn');
72
- this.autoOut = new AutoStruct(builtinVertexOut, undefined, undefined,
72
+ this.autoOut = new AutoStruct(builtinVertexOut, undefined, locations,
73
73
  /* autoInterpolateIntegers */ true);
74
74
  setName(this.autoOut, 'VertexOut');
75
75
  }
@@ -2,7 +2,8 @@ import { WgslTypeError } from "../../errors.js";
2
2
  import { setName } from "../../shared/meta.js";
3
3
  import { $getNameForward, $gpuCallable, $internal } from "../../shared/symbols.js";
4
4
  import { coerceToSnippet } from "../../tgsl/generationHelpers.js";
5
- import { isKnownAtComptime, NormalState } from "../../types.js";
5
+ import { stringifySnippet } from "../../tgsl/stringifySnippet.js";
6
+ import { asComptime, NormalState } from "../../types.js";
6
7
  export function isComptimeFn(value) {
7
8
  return !!value?.[$internal]?.isComptime;
8
9
  }
@@ -38,15 +39,16 @@ export function comptime(func) {
38
39
  impl[$getNameForward] = func;
39
40
  impl[$gpuCallable] = {
40
41
  call(ctx, args) {
41
- if (!args.every((s) => isKnownAtComptime(s))) {
42
+ const comptimeArgs = args.map((s) => asComptime(s));
43
+ if (!comptimeArgs.every((s) => s !== undefined)) {
42
44
  throw new WgslTypeError(`Called comptime function with runtime-known values: ${args
43
- .filter((s) => !isKnownAtComptime(s))
44
- .map((s) => `'${s.value}'`)
45
+ .filter((_, idx) => comptimeArgs[idx] === undefined)
46
+ .map((s) => `'${stringifySnippet(s)}'`)
45
47
  .join(', ')}`);
46
48
  }
47
49
  ctx.pushMode(new NormalState());
48
50
  try {
49
- return coerceToSnippet(func(...args.map((s) => s.value)));
51
+ return coerceToSnippet(func(...comptimeArgs.map((s) => s.value)));
50
52
  }
51
53
  finally {
52
54
  ctx.popMode();
@@ -3,7 +3,7 @@ import { isPtr } from "../../data/wgslTypes.js";
3
3
  import { setName } from "../../shared/meta.js";
4
4
  import { $gpuCallable } from "../../shared/symbols.js";
5
5
  import { tryConvertSnippet } from "../../tgsl/conversion.js";
6
- import { isKnownAtComptime, NormalState } from "../../types.js";
6
+ import { asComptime, NormalState } from "../../types.js";
7
7
  export function callableSchema(options) {
8
8
  const impl = ((...args) => {
9
9
  return options.normalImpl(...args);
@@ -30,10 +30,11 @@ export function callableSchema(options) {
30
30
  return tryConvertSnippet(ctx, s, argType, false);
31
31
  });
32
32
  let result;
33
- if (converted.every((s) => isKnownAtComptime(s))) {
33
+ const comptimeArgs = converted.map((s) => asComptime(s));
34
+ if (comptimeArgs.every((s) => s !== undefined)) {
34
35
  ctx.pushMode(new NormalState());
35
36
  try {
36
- result = snip(options.normalImpl(...converted.map((s) => s.value)), options.schema(),
37
+ result = snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), options.schema(),
37
38
  // Functions give up ownership of their return value
38
39
  /* origin */ 'constant');
39
40
  }
@@ -3,7 +3,7 @@ import { setName } from "../../shared/meta.js";
3
3
  import { $gpuCallable } from "../../shared/symbols.js";
4
4
  import { tryConvertSnippet } from "../../tgsl/conversion.js";
5
5
  import { concretize } from "../../tgsl/generationHelpers.js";
6
- import { isKnownAtComptime, NormalState } from "../../types.js";
6
+ import { asComptime, NormalState } from "../../types.js";
7
7
  import { isPtr } from "../../data/wgslTypes.js";
8
8
  export class MissingCpuImplError extends Error {
9
9
  constructor(message) {
@@ -11,6 +11,7 @@ export class MissingCpuImplError extends Error {
11
11
  this.name = this.constructor.name;
12
12
  }
13
13
  }
14
+ /*#__NO_SIDE_EFFECTS__*/
14
15
  export function dualImpl(options) {
15
16
  const impl = ((...args) => {
16
17
  if (typeof options.normalImpl === 'string') {
@@ -43,25 +44,26 @@ export function dualImpl(options) {
43
44
  }
44
45
  return tryConvertSnippet(ctx, s, argType, !options.ignoreImplicitCastWarning);
45
46
  });
46
- if (!options.noComptime &&
47
- converted.every((s) => isKnownAtComptime(s)) &&
48
- typeof options.normalImpl === 'function') {
49
- ctx.pushMode(new NormalState());
50
- try {
51
- return snip(options.normalImpl(...converted.map((s) => s.value)), returnType,
52
- // Functions give up ownership of their return value
53
- /* origin */ 'constant', options.sideEffects);
54
- }
55
- catch (e) {
56
- // cpuImpl may in some cases be present but implemented only partially.
57
- // In that case, if the MissingCpuImplError is thrown, we fallback to codegenImpl.
58
- // If it is any other error, we just rethrow.
59
- if (!(e instanceof MissingCpuImplError)) {
60
- throw e;
47
+ if (!options.noComptime && typeof options.normalImpl === 'function') {
48
+ const comptimeArgs = converted.map((s) => asComptime(s));
49
+ if (comptimeArgs.every((s) => s !== undefined)) {
50
+ ctx.pushMode(new NormalState());
51
+ try {
52
+ return snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), returnType,
53
+ // Functions give up ownership of their return value
54
+ /* origin */ 'constant', options.sideEffects);
55
+ }
56
+ catch (e) {
57
+ // cpuImpl may in some cases be present but implemented only partially.
58
+ // In that case, if the MissingCpuImplError is thrown, we fallback to codegenImpl.
59
+ // If it is any other error, we just rethrow.
60
+ if (!(e instanceof MissingCpuImplError)) {
61
+ throw e;
62
+ }
63
+ }
64
+ finally {
65
+ ctx.popMode('normal');
61
66
  }
62
- }
63
- finally {
64
- ctx.popMode('normal');
65
67
  }
66
68
  }
67
69
  const possibleSideEffects = options.sideEffects || args.some((a) => a.possibleSideEffects);
@@ -7,6 +7,16 @@ export type WithLocations<T extends Record<string, BaseData>> = {
7
7
  export type IOLayoutToSchema<T> = T extends BaseData ? HasCustomLocation<T> extends true ? T : Decorate<T, Location<0>> : T extends Record<string, BaseData> ? WgslStruct<WithLocations<T>> : T extends {
8
8
  type: 'void';
9
9
  } ? void : never;
10
+ /**
11
+ * Assigns locations to members.
12
+ * The priority of assigned location is as follows:
13
+ * - location already present in member,
14
+ * - location provided in `locations`,
15
+ * - a free number.
16
+ *
17
+ * Assumes `locations` are consistent with already decorated `members`,
18
+ * throws if a location is repeated.
19
+ */
10
20
  export declare function withLocations<T extends BaseData>(members: Record<string, T> | undefined, locations?: Record<string, number>, autoInterpolateIntegers?: boolean): Record<string, BaseData>;
11
21
  export declare function separateBuiltins(schema: Record<string, BaseData>, locations?: Record<string, number>): SeparatedEntryArgs;
12
22
  export declare function separateAllAsPositional(schema: Record<string, BaseData>): SeparatedEntryArgs;
@@ -3,33 +3,42 @@ import { isBuiltin } from "../../data/attributes.js";
3
3
  import { getCustomLocation, isData } from "../../data/dataTypes.js";
4
4
  import { INTERNAL_createStruct } from "../../data/struct.js";
5
5
  import { isDecorated, isInteger, isIntegerVec, isInterpolateAttrib, isVoid, } from "../../data/wgslTypes.js";
6
+ /**
7
+ * Assigns locations to members.
8
+ * The priority of assigned location is as follows:
9
+ * - location already present in member,
10
+ * - location provided in `locations`,
11
+ * - a free number.
12
+ *
13
+ * Assumes `locations` are consistent with already decorated `members`,
14
+ * throws if a location is repeated.
15
+ */
6
16
  export function withLocations(members, locations = {}, autoInterpolateIntegers = false) {
7
17
  let nextLocation = 0;
8
- const usedCustomLocations = new Set();
9
- return Object.fromEntries(Object.entries(members ?? {})
18
+ const usedCustomLocations = new Set([
19
+ ...Object.values(locations),
20
+ ...Object.values(members ?? {})
21
+ .map(getCustomLocation)
22
+ .filter((v) => v !== undefined),
23
+ ]);
24
+ const entries = Object.entries(members ?? {})
10
25
  .map(([key, member]) => {
11
- const customLocation = getCustomLocation(member);
12
- if (customLocation !== undefined) {
13
- if (usedCustomLocations.has(customLocation)) {
14
- throw new Error('Duplicate custom location attributes found');
15
- }
16
- usedCustomLocations.add(customLocation);
17
- }
18
- return [
19
- key,
20
- autoInterpolateIntegers ? withFlatInterpolationForInteger(member) : member,
21
- ];
26
+ // Interpolate
27
+ const interpolated = autoInterpolateIntegers
28
+ ? withFlatInterpolationForInteger(member)
29
+ : member;
30
+ return [key, interpolated];
22
31
  })
23
32
  .map(([key, member]) => {
33
+ // Assign locations
24
34
  if (isBuiltin(member)) {
25
- // skipping builtins
26
35
  return [key, member];
27
36
  }
28
37
  if (getCustomLocation(member) !== undefined) {
29
38
  // this member is already marked
30
39
  return [key, member];
31
40
  }
32
- if (locations[key]) {
41
+ if (locations[key] !== undefined) {
33
42
  // location has been determined by a previous procedure
34
43
  return [key, location(locations[key], member)];
35
44
  }
@@ -37,7 +46,19 @@ export function withLocations(members, locations = {}, autoInterpolateIntegers =
37
46
  nextLocation++;
38
47
  }
39
48
  return [key, location(nextLocation++, member)];
40
- }));
49
+ });
50
+ // Check for duplicate locations
51
+ const used = new Map();
52
+ entries.forEach(([key, member]) => {
53
+ const location = getCustomLocation(member);
54
+ if (location !== undefined) {
55
+ if (used.has(location)) {
56
+ throw new Error(`Location '${location}' is used by multiple keys: '${used.get(location)}', '${key}'.`);
57
+ }
58
+ used.set(location, key);
59
+ }
60
+ });
61
+ return Object.fromEntries(entries);
41
62
  }
42
63
  export function separateBuiltins(schema, locations = {}) {
43
64
  const positionalArgs = [];
@@ -6,7 +6,7 @@ import type { Prettify } from '../../shared/utilityTypes.ts';
6
6
  import type { DualFn } from '../../types.ts';
7
7
  import { type Providing } from '../slot/slotTypes.ts';
8
8
  import type { AnyFn, Implementation, InferArgs, InferImplSchema, InheritArgNames } from './fnTypes.ts';
9
- import type { Withable } from '../root/rootTypes.ts';
9
+ import type { Configurable, Withable } from '../root/rootTypes.ts';
10
10
  /**
11
11
  * Describes a function signature (its arguments and return type)
12
12
  */
@@ -19,6 +19,7 @@ type TgpuFnShellHeader<Args extends BaseData[], Return extends BaseData> = {
19
19
  * Describes a function signature (its arguments and return type).
20
20
  * Allows creating tgpu functions by calling this shell
21
21
  * and passing the implementation (as WGSL string or JS function) as the argument.
22
+ * An already shelled function is reused when its argument and return schemas match.
22
23
  */
23
24
  export type TgpuFnShell<Args extends BaseData[], Return extends BaseData> = TgpuFnShellHeader<Args, Return> & (<T extends (...args: InferArgs<Args>) => InferGPU<Return>>(implementation: T) => TgpuFn<Prettify<InheritArgNames<(...args: Args) => Return, T>>['result']>) & ((implementation: string) => TgpuFn<(...args: Args) => Return>) & ((strings: TemplateStringsArray, ...values: unknown[]) => TgpuFn<(...args: Args) => Return>);
24
25
  interface TgpuFnBase<ImplSchema extends AnyFn> extends TgpuNamable, Withable<TgpuFn<ImplSchema>> {
@@ -29,6 +30,11 @@ interface TgpuFnBase<ImplSchema extends AnyFn> extends TgpuNamable, Withable<Tgp
29
30
  readonly shell: TgpuFnShellHeader<Parameters<ImplSchema>, Extract<ReturnType<ImplSchema>, BaseData>>;
30
31
  readonly [$providing]?: Providing | undefined;
31
32
  $uses(dependencyMap: Record<string, unknown>): this;
33
+ /**
34
+ * Applies a configuration transform to the slots and accessors this function reads,
35
+ * as `root.pipe` does to a pipeline's.
36
+ */
37
+ pipe(transform: (cfg: Configurable) => Configurable): TgpuFn<ImplSchema>;
32
38
  }
33
39
  export type TgpuFn<ImplSchema extends AnyFn = (...args: any[]) => any> = DualFn<InferImplSchema<ImplSchema>> & TgpuFnBase<ImplSchema>;
34
40
  /**
@@ -40,6 +46,11 @@ export interface TgpuGenericFn<T extends AnyFn> extends TgpuNamable, Withable<Tg
40
46
  };
41
47
  readonly [$providing]?: Providing | undefined;
42
48
  readonly resourceType: 'generic-function';
49
+ /**
50
+ * Applies a configuration transform to the slots and accessors this function reads,
51
+ * as `root.pipe` does to a pipeline's.
52
+ */
53
+ pipe(transform: (cfg: Configurable) => Configurable): TgpuGenericFn<T>;
43
54
  (...args: Parameters<T>): ReturnType<T>;
44
55
  }
45
56
  export declare function fn<Args extends BaseData[] | []>(argTypes: Args, returnType?: undefined): TgpuFnShell<Args, Void>;
@@ -1,4 +1,5 @@
1
1
  import { schemaCallWrapper } from "../../data/schemaCallWrapper.js";
2
+ import { schemasEqualNominally } from "../../data/schemasEqual.js";
2
3
  import { Void } from "../../data/wgslTypes.js";
3
4
  import { ExecutionError } from "../../errors.js";
4
5
  import { provideInsideTgpuFn } from "../../execMode.js";
@@ -12,6 +13,7 @@ import { dualImpl } from "./dualImpl.js";
12
13
  import { createFnCore } from "./fnCore.js";
13
14
  import { stripTemplate } from "./templateUtils.js";
14
15
  import { comptime } from "./comptime.js";
16
+ import { ConfigurableImpl } from "../root/configurableImpl.js";
15
17
  export function fn(argTypesOrCallback, returnType) {
16
18
  if (typeof argTypesOrCallback === 'function') {
17
19
  return createGenericFn(argTypesOrCallback, []);
@@ -39,7 +41,19 @@ export function isGenericFn(value) {
39
41
  function stringifyPair([slot, value]) {
40
42
  return `${getName(slot) ?? '<unnamed>'}=${value}`;
41
43
  }
44
+ function bindingsOf(transform) {
45
+ return transform(new ConfigurableImpl([])).bindings;
46
+ }
42
47
  function createFn(shell, _implementation) {
48
+ if (isTgpuFn(_implementation)) {
49
+ const innerShell = _implementation.shell;
50
+ if (!schemasEqualNominally(innerShell.returnType, shell.returnType) ||
51
+ innerShell.argTypes.length !== shell.argTypes.length ||
52
+ !shell.argTypes.every((type, index) => schemasEqualNominally(type, innerShell.argTypes[index]))) {
53
+ throw new Error('Cannot wrap a shelled function with a different signature');
54
+ }
55
+ return _implementation;
56
+ }
43
57
  let pairs = [];
44
58
  // Unwrapping generic functions
45
59
  let implementation;
@@ -68,6 +82,7 @@ function createFn(shell, _implementation) {
68
82
  const s = isAccessor(slot) || isMutableAccessor(slot) ? slot.slot : slot;
69
83
  return createBoundFunction(fn, [[s, value]]);
70
84
  }),
85
+ pipe: comptime((transform) => createBoundFunction(fn, bindingsOf(transform))),
71
86
  [$resolve](ctx) {
72
87
  if (typeof implementation === 'string') {
73
88
  addArgTypesToExternals(implementation, shell.argTypes, core);
@@ -129,6 +144,7 @@ function createBoundFunction(innerFn, pairs) {
129
144
  const s = isAccessor(slot) || isMutableAccessor(slot) ? slot.slot : slot;
130
145
  return createBoundFunction(innerFn, [...pairs, [s, value]]);
131
146
  }),
147
+ pipe: comptime((transform) => createBoundFunction(innerFn, [...pairs, ...bindingsOf(transform)])),
132
148
  };
133
149
  const call = dualImpl({
134
150
  name: undefined, // setting name here would override autonaming
@@ -170,10 +186,11 @@ function createGenericFn(inner, pairs) {
170
186
  [$resolve](ctx) {
171
187
  return ctx.resolve(inner);
172
188
  },
173
- with(slot, value) {
189
+ with: comptime((slot, value) => {
174
190
  const s = isAccessor(slot) || isMutableAccessor(slot) ? slot.slot : slot;
175
191
  return createGenericFn(inner, [...pairs, [s, value]]);
176
- },
192
+ }),
193
+ pipe: comptime((transform) => createGenericFn(inner, [...pairs, ...bindingsOf(transform)])),
177
194
  };
178
195
  const call = (...args) => {
179
196
  return inner(...args);
@@ -41,6 +41,7 @@ export function INTERNAL_restoreComputePipeline(soul, ctx) {
41
41
  }
42
42
  class TgpuComputePipelineImpl {
43
43
  [$internal];
44
+ #unbound;
44
45
  [$soul];
45
46
  resourceType = 'compute-pipeline';
46
47
  [$getNameForward];
@@ -86,7 +87,9 @@ class TgpuComputePipelineImpl {
86
87
  with(first, resource) {
87
88
  const internals = this[$internal];
88
89
  if (isTgpuComputePass(first)) {
89
- return this.#withPriors({ pass: first, encoder: undefined });
90
+ const bound = this.#withPriors({ pass: first, encoder: undefined });
91
+ bound.#unbound = this.#unbound ?? this;
92
+ return bound;
90
93
  }
91
94
  if (isTgpuCommandEncoder(first)) {
92
95
  return this.#withPriors({ pass: undefined, encoder: first });
@@ -157,7 +160,7 @@ class TgpuComputePipelineImpl {
157
160
  #execute(dispatch) {
158
161
  const { core, priors, root } = this[$internal];
159
162
  if (priors.pass) {
160
- emitComputeDispatch(root, priors.pass[$internal], this, dispatch);
163
+ emitComputeDispatch(root, priors.pass[$internal], this.#unbound ?? this, dispatch);
161
164
  return;
162
165
  }
163
166
  const encoder = priors.encoder ?? INTERNAL_createCommandEncoder(root);
@@ -286,8 +286,10 @@ declare class RenderPipelineCore implements SelfResolvable {
286
286
  };
287
287
  }
288
288
  /**
289
- * Assumes vertexOut and fragmentIn are matching when it comes to the keys, that is fragmentIn's keyset is a subset of vertexOut's
290
- * Logs a warning, when they don't match in terms of custom locations
289
+ * Throws, when vertexOut and fragmentIn don't match in terms of custom locations.
290
+ *
291
+ * @privateRemarks
292
+ * Note that vertexOut is undefined in shellless functions.
291
293
  */
292
294
  export declare function matchUpVaryingLocations(vertexOut: TgpuVertexFn.Out | undefined, fragmentIn: TgpuFragmentFn.In | undefined, vertexFnName: string, fragmentFnName: string): Record<string, number>;
293
295
  export {};
@@ -56,6 +56,7 @@ export function INTERNAL_restoreRenderPipeline(soul, ctx) {
56
56
  }
57
57
  class TgpuRenderPipelineImpl {
58
58
  [$internal];
59
+ #unbound;
59
60
  [$soul];
60
61
  resourceType = 'render-pipeline';
61
62
  [$getNameForward];
@@ -110,7 +111,9 @@ class TgpuRenderPipelineImpl {
110
111
  with(first, resource) {
111
112
  const internals = this[$internal];
112
113
  if (isTgpuRenderCommands(first)) {
113
- return this.#withPriors({ pass: first, encoder: undefined });
114
+ const bound = this.#withPriors({ pass: first, encoder: undefined });
115
+ bound.#unbound = this.#unbound ?? this;
116
+ return bound;
114
117
  }
115
118
  if (isTgpuCommandEncoder(first)) {
116
119
  return this.#withPriors({ pass: undefined, encoder: first });
@@ -181,7 +184,7 @@ class TgpuRenderPipelineImpl {
181
184
  withStencilReference(reference) {
182
185
  return this.#withPriors({ stencilReference: reference });
183
186
  }
184
- withIndexBuffer(buffer, indexFormatOrOffset, offsetElementsOrSizeBytes, sizeElementsOrUndefined) {
187
+ withIndexBuffer(buffer, indexFormatOrOffset, offsetBytesOrSizeElements, sizeBytesOrUndefined) {
185
188
  if (isGPUBuffer(buffer)) {
186
189
  if (typeof indexFormatOrOffset !== 'string') {
187
190
  throw new Error('If a GPUBuffer is passed, indexFormat must be provided.');
@@ -190,8 +193,8 @@ class TgpuRenderPipelineImpl {
190
193
  indexBuffer: {
191
194
  buffer,
192
195
  indexFormat: indexFormatOrOffset,
193
- offsetBytes: offsetElementsOrSizeBytes,
194
- sizeBytes: sizeElementsOrUndefined,
196
+ offsetBytes: offsetBytesOrSizeElements,
197
+ sizeBytes: sizeBytesOrUndefined,
195
198
  },
196
199
  });
197
200
  }
@@ -207,8 +210,8 @@ class TgpuRenderPipelineImpl {
207
210
  offsetBytes: indexFormatOrOffset !== undefined
208
211
  ? indexFormatOrOffset * sizeOf(elementType)
209
212
  : undefined,
210
- sizeBytes: sizeElementsOrUndefined !== undefined
211
- ? sizeElementsOrUndefined * sizeOf(elementType)
213
+ sizeBytes: offsetBytesOrSizeElements !== undefined
214
+ ? offsetBytesOrSizeElements * sizeOf(elementType)
212
215
  : undefined,
213
216
  },
214
217
  });
@@ -235,7 +238,7 @@ class TgpuRenderPipelineImpl {
235
238
  #execute(usesIndexBuffer, emit) {
236
239
  const { core, priors, root } = this[$internal];
237
240
  if (priors.pass) {
238
- emitRenderDraw(root, priors.pass[$internal], this, usesIndexBuffer, emit);
241
+ emitRenderDraw(root, priors.pass[$internal], this.#unbound ?? this, usesIndexBuffer, emit);
239
242
  return;
240
243
  }
241
244
  // checked up front so a rejected draw never leaves a half-recorded pass behind
@@ -469,8 +472,10 @@ class RenderPipelineCore {
469
472
  }
470
473
  }
471
474
  /**
472
- * Assumes vertexOut and fragmentIn are matching when it comes to the keys, that is fragmentIn's keyset is a subset of vertexOut's
473
- * Logs a warning, when they don't match in terms of custom locations
475
+ * Throws, when vertexOut and fragmentIn don't match in terms of custom locations.
476
+ *
477
+ * @privateRemarks
478
+ * Note that vertexOut is undefined in shellless functions.
474
479
  */
475
480
  export function matchUpVaryingLocations(vertexOut = {}, fragmentIn = {}, vertexFnName, fragmentFnName) {
476
481
  const locations = {};
@@ -495,13 +500,13 @@ export function matchUpVaryingLocations(vertexOut = {}, fragmentIn = {}, vertexF
495
500
  saveLocation(key, customLocation);
496
501
  }
497
502
  else if (locations[key] !== customLocation) {
498
- logger.warn('locations-mismatched', `Mismatched location between vertexFn (${vertexFnName}) output (${locations[key]}) and fragmentFn (${fragmentFnName}) input (${customLocation}) for the key "${key}", using the location set on vertex output.`);
503
+ throw new Error(`Mismatched location between vertexFn (${vertexFnName}) output (${locations[key]}) and fragmentFn (${fragmentFnName}) input (${customLocation}) for the key "${key}".`);
499
504
  }
500
505
  }
501
506
  // automatically assign remaining locations to the rest
502
507
  let nextLocation = 0;
503
- for (const key of Object.keys(vertexOut ?? {})) {
504
- if (isBuiltin(vertexOut[key]) || locations[key] !== undefined) {
508
+ for (const [key, value] of [...Object.entries(vertexOut), ...Object.entries(fragmentIn)]) {
509
+ if (isBuiltin(value) || locations[key] !== undefined) {
505
510
  continue;
506
511
  }
507
512
  while (usedLocations.has(nextLocation)) {
@@ -41,14 +41,27 @@ async function readTimestamps(querySet, registrations) {
41
41
  if (!querySet.available) {
42
42
  return;
43
43
  }
44
- const result = await querySet.read();
44
+ let result;
45
+ try {
46
+ result = await querySet.read();
47
+ }
48
+ catch {
49
+ // The read was cancelled or failed (e.g. the device was destroyed or lost mid-read).
50
+ // Genuine validation errors are already reported through the device's error handling.
51
+ return;
52
+ }
45
53
  for (const { priors, callback } of registrations) {
46
54
  const start = result[priors.timestampWrites?.beginningOfPassWriteIndex ?? 0];
47
55
  const end = result[priors.timestampWrites?.endOfPassWriteIndex ?? 1];
48
56
  if (start === undefined || end === undefined) {
49
57
  throw new Error('QuerySet did not return valid timestamps.');
50
58
  }
51
- await callback(start, end);
59
+ try {
60
+ await callback(start, end);
61
+ }
62
+ catch (err) {
63
+ console.error('An error was thrown from a performance callback (withPerformanceCallback). Errors thrown here cannot be caught by the caller, so handle them within the callback itself.', err);
64
+ }
52
65
  }
53
66
  }
54
67
  /** Returns false when the encoder is one we cannot defer work to, meaning the callback never fires */
@@ -34,8 +34,15 @@ function requiredAlignOf(schema) {
34
34
  * See https://www.w3.org/TR/WGSL/#address-space-layout-constraints
35
35
  */
36
36
  export function warnIfNotUniformAligned(schema) {
37
+ if (!logger.isEnabled('uniform-schema-misaligned')) {
38
+ // Silenced by default in production, and computing memory layouts isn't free
39
+ return;
40
+ }
41
+ checkUniformAlignment(schema);
42
+ }
43
+ function checkUniformAlignment(schema) {
37
44
  if (isWgslArray(schema)) {
38
- warnIfNotUniformAligned(schema.elementType);
45
+ checkUniformAlignment(schema.elementType);
39
46
  const stride = roundUp(sizeOf(schema.elementType), alignmentOf(schema.elementType));
40
47
  if (stride % 16 !== 0) {
41
48
  logger.warn('uniform-schema-misaligned', `\
@@ -45,7 +52,7 @@ To address this, put the element schema in a struct and wrap the prop in 'd.alig
45
52
  }
46
53
  }
47
54
  if (isWgslStruct(schema)) {
48
- Object.values(schema.propTypes).forEach(warnIfNotUniformAligned);
55
+ Object.values(schema.propTypes).forEach(checkUniformAlignment);
49
56
  Object.entries(schema.propTypes).forEach(([key, value]) => {
50
57
  const offset = memoryLayoutOf(schema, (schema) => schema[key]).offset;
51
58
  const requiredAlignment = requiredAlignOf(value);
@@ -11,7 +11,6 @@ export class ConfigurableImpl {
11
11
  ]);
12
12
  }
13
13
  pipe(transform) {
14
- const newCfg = transform(this);
15
- return new ConfigurableImpl([...this.bindings, ...newCfg.bindings]);
14
+ return transform(this);
16
15
  }
17
16
  }
@@ -1,5 +1,5 @@
1
1
  import { type TgpuQuerySet } from '../querySet/querySet.ts';
2
- import type { v3u, Vec3u } from '../../data/wgslTypes.ts';
2
+ import type { v3u } from '../../data/wgslTypes.ts';
3
3
  import { $getNameForward, $internal, $soul } from '../../shared/symbols.ts';
4
4
  import type { TgpuBindGroup } from '../../tgpuBindGroupLayout.ts';
5
5
  import type { LogGeneratorOptions } from '../../tgsl/consoleLog/types.ts';
@@ -12,7 +12,7 @@ export declare class TgpuGuardedComputePipelineImpl<TArgs extends number[]> impl
12
12
  #private;
13
13
  readonly resourceType = "guarded-compute-pipeline";
14
14
  readonly [$soul]: TgpuGuardedComputePipelineSoul;
15
- constructor(root: ExperimentalTgpuRoot, pipeline: TgpuComputePipeline, sizeUniform: TgpuUniform<Vec3u>, workgroupSize: v3u);
15
+ constructor(root: ExperimentalTgpuRoot, pipeline: TgpuComputePipeline, size: TgpuGuardedComputePipelineSoul['size'], workgroupSize: v3u);
16
16
  with(bindGroup: TgpuBindGroup): TgpuGuardedComputePipeline<TArgs>;
17
17
  withPerformanceCallback(callback: (start: bigint, end: bigint) => void | Promise<void>): TgpuGuardedComputePipeline<TArgs>;
18
18
  withTimestampWrites(options: {
@@ -24,7 +24,7 @@ export declare class TgpuGuardedComputePipelineImpl<TArgs extends number[]> impl
24
24
  initAsync(): Promise<void>;
25
25
  initSync(): void;
26
26
  get pipeline(): TgpuComputePipeline;
27
- get sizeUniform(): TgpuUniform<Vec3u>;
27
+ get sizeUniform(): TgpuUniform<import("../../data/wgslTypes.ts").Vec3u>;
28
28
  [$internal]: boolean;
29
29
  get [$getNameForward](): TgpuComputePipeline;
30
30
  $name(label: string): this;
package/core/root/init.js CHANGED
@@ -44,15 +44,13 @@ export class TgpuGuardedComputePipelineImpl {
44
44
  resourceType = 'guarded-compute-pipeline';
45
45
  [$soul];
46
46
  #root;
47
- #lastSize;
48
- constructor(root, pipeline, sizeUniform, workgroupSize) {
47
+ constructor(root, pipeline, size, workgroupSize) {
49
48
  this.#root = root;
50
- this.#lastSize = vec3u();
51
49
  this[$soul] = {
52
50
  type: 'guarded-compute-pipeline',
53
51
  device: root.device,
54
52
  pipeline,
55
- sizeUniform,
53
+ size,
56
54
  workgroupSize,
57
55
  label: undefined,
58
56
  };
@@ -61,22 +59,23 @@ export class TgpuGuardedComputePipelineImpl {
61
59
  if (!isBindGroup(bindGroup)) {
62
60
  throw new Error('Guarded pipelines only accept bind groups in .with(). To record into passes or encoders, use a regular compute pipeline.');
63
61
  }
64
- return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.with(bindGroup), this[$soul].sizeUniform, this[$soul].workgroupSize);
62
+ return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.with(bindGroup), this[$soul].size, this[$soul].workgroupSize);
65
63
  }
66
64
  withPerformanceCallback(callback) {
67
- return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.withPerformanceCallback(callback), this[$soul].sizeUniform, this[$soul].workgroupSize);
65
+ return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.withPerformanceCallback(callback), this[$soul].size, this[$soul].workgroupSize);
68
66
  }
69
67
  withTimestampWrites(options) {
70
- return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.withTimestampWrites(options), this[$soul].sizeUniform, this[$soul].workgroupSize);
68
+ return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.withTimestampWrites(options), this[$soul].size, this[$soul].workgroupSize);
71
69
  }
72
70
  dispatchThreads(...threads) {
73
71
  const sanitizedSize = toVec3(threads);
74
72
  const workgroupCount = ceil(vec3f(sanitizedSize).div(vec3f(this[$soul].workgroupSize)));
75
- if (!allEq(sanitizedSize, this.#lastSize)) {
73
+ const { size } = this[$soul];
74
+ if (!allEq(sanitizedSize, size.lastValue)) {
76
75
  // Only updating the size if it has changed from the last
77
76
  // invocation. This removes the need for flushing.
78
- this.#lastSize = sanitizedSize;
79
- this[$soul].sizeUniform.write(sanitizedSize);
77
+ size.lastValue = sanitizedSize;
78
+ size.uniform.write(sanitizedSize);
80
79
  }
81
80
  this[$soul].pipeline.dispatchWorkgroups(workgroupCount.x, workgroupCount.y, workgroupCount.z);
82
81
  }
@@ -90,7 +89,7 @@ export class TgpuGuardedComputePipelineImpl {
90
89
  return this[$soul].pipeline;
91
90
  }
92
91
  get sizeUniform() {
93
- return this[$soul].sizeUniform;
92
+ return this[$soul].size.uniform;
94
93
  }
95
94
  [$internal] = true;
96
95
  get [$getNameForward]() {
@@ -105,7 +104,7 @@ export function INTERNAL_restoreRoot(soul, ctx) {
105
104
  return ctx.getRoot(soul.device);
106
105
  }
107
106
  export function INTERNAL_restoreGuardedComputePipeline(soul, ctx) {
108
- return new TgpuGuardedComputePipelineImpl(ctx.getRoot(soul.device), soul.pipeline, soul.sizeUniform, soul.workgroupSize);
107
+ return new TgpuGuardedComputePipelineImpl(ctx.getRoot(soul.device), soul.pipeline, soul.size, soul.workgroupSize);
109
108
  }
110
109
  class WithBindingImpl {
111
110
  #getRoot;
@@ -154,7 +153,7 @@ class WithBindingImpl {
154
153
  }`.$uses({ sizeUniform, wrappedCallback });
155
154
  // NOTE: in certain setups, unplugin can run on package typegpu, so we have to avoid auto-naming triggering here
156
155
  const pipeline = (() => this.createComputePipeline({ compute: mainCompute }))();
157
- return new TgpuGuardedComputePipelineImpl(root, pipeline, sizeUniform, workgroupSize);
156
+ return new TgpuGuardedComputePipelineImpl(root, pipeline, { uniform: sizeUniform, lastValue: vec3u() }, workgroupSize);
158
157
  }
159
158
  pipe(transform) {
160
159
  const newCfg = transform(new ConfigurableImpl([]));
@@ -37,7 +37,10 @@ export interface TgpuRootSoul extends TgpuSoul<'root'> {
37
37
  export interface TgpuGuardedComputePipelineSoul extends TgpuSoul<'guarded-compute-pipeline'> {
38
38
  readonly device: GPUDevice;
39
39
  readonly pipeline: TgpuComputePipeline;
40
- readonly sizeUniform: TgpuUniform<Vec3u>;
40
+ readonly size: {
41
+ uniform: TgpuUniform<Vec3u>;
42
+ lastValue: v3u;
43
+ };
41
44
  readonly workgroupSize: v3u;
42
45
  }
43
46
  export interface TgpuGuardedComputePipeline<TArgs extends number[] = number[]> extends TgpuNamable {