typegpu 0.12.8 → 0.12.10

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 (119) hide show
  1. package/common/attachAutoResizer.d.ts +33 -0
  2. package/common/attachAutoResizer.js +83 -0
  3. package/common/index.d.ts +1 -0
  4. package/common/index.js +1 -0
  5. package/common/writeSoA.js +4 -3
  6. package/core/commandEncoder/commandEncoder.d.ts +1 -1
  7. package/core/declare/tgpuDeclare.d.ts +10 -7
  8. package/core/declare/tgpuDeclare.js +25 -10
  9. package/core/function/comptime.d.ts +2 -0
  10. package/core/function/comptime.js +29 -24
  11. package/core/function/createCallableSchema.js +32 -37
  12. package/core/function/dualImpl.js +45 -44
  13. package/core/function/tgpuComputeFn.d.ts +0 -3
  14. package/core/function/tgpuFn.d.ts +1 -0
  15. package/core/function/tgpuFn.js +14 -4
  16. package/core/function/tgpuFragmentFn.d.ts +1 -1
  17. package/core/function/tgpuVertexFn.d.ts +1 -1
  18. package/core/pipeline/computePipeline.js +5 -2
  19. package/core/pipeline/drawState.js +1 -1
  20. package/core/pipeline/renderPipeline.js +5 -2
  21. package/core/pipeline/webgpuLimitations.js +11 -3
  22. package/core/resolve/externals.js +4 -0
  23. package/core/resolve/namespace.d.ts +4 -0
  24. package/core/resolve/namespace.js +1 -2
  25. package/core/resolve/stitch.js +13 -8
  26. package/core/root/init.d.ts +3 -3
  27. package/core/root/init.js +12 -13
  28. package/core/root/rootTypes.d.ts +44 -37
  29. package/core/slot/accessor.js +4 -4
  30. package/core/texture/texture.d.ts +3 -3
  31. package/core/texture/texture.js +60 -44
  32. package/core/texture/textureFormats.d.ts +4 -3
  33. package/core/texture/textureFormats.js +17 -6
  34. package/core/texture/textureWrite.d.ts +9 -0
  35. package/core/texture/textureWrite.js +21 -0
  36. package/core/unroll/tgpuUnroll.js +2 -4
  37. package/core/vertexLayout/vertexAttribute.d.ts +1 -4
  38. package/core/vertexLayout/vertexLayout.js +11 -30
  39. package/data/alignmentOf.d.ts +1 -1
  40. package/data/alignmentOf.js +5 -12
  41. package/data/array.js +34 -2
  42. package/data/attributes.d.ts +16 -3
  43. package/data/attributes.js +11 -2
  44. package/data/compiledIO.js +3 -3
  45. package/data/dataIO.js +77 -111
  46. package/data/dataTypes.d.ts +0 -2
  47. package/data/dataTypes.js +3 -3
  48. package/data/disarray.js +2 -0
  49. package/data/index.d.ts +4 -3
  50. package/data/index.js +3 -2
  51. package/data/offsetUtils.js +23 -13
  52. package/data/offsets.js +1 -2
  53. package/data/partialIO.js +2 -3
  54. package/data/ref.js +35 -37
  55. package/data/schemaCallWrapper.js +2 -2
  56. package/data/schemaMemoryLayout.d.ts +6 -1
  57. package/data/schemaMemoryLayout.js +23 -14
  58. package/data/schemasEqual.d.ts +37 -0
  59. package/data/schemasEqual.js +122 -0
  60. package/data/sizeOf.d.ts +1 -1
  61. package/data/sizeOf.js +2 -3
  62. package/data/snippet.d.ts +1 -1
  63. package/data/struct.js +27 -1
  64. package/data/unstruct.js +2 -0
  65. package/data/vectorImpl.js +45 -21
  66. package/data/vertexFormatData.js +7 -9
  67. package/data/wgslTypes.d.ts +28 -13
  68. package/data/wgslTypes.js +33 -39
  69. package/extension.d.ts +0 -4
  70. package/package.json +2 -2
  71. package/resolutionCtx.d.ts +1 -1
  72. package/resolutionCtx.js +26 -7
  73. package/serial/restore.d.ts +4 -3
  74. package/serial/restore.js +2 -1
  75. package/shared/meta.js +1 -1
  76. package/shared/symbols.d.ts +5 -0
  77. package/shared/symbols.js +6 -1
  78. package/shared/utilityTypes.d.ts +0 -6
  79. package/std/bitcast.d.ts +1 -1
  80. package/std/comptime.d.ts +67 -0
  81. package/std/comptime.js +88 -0
  82. package/std/environment.js +2 -4
  83. package/std/index.d.ts +2 -0
  84. package/std/index.js +2 -0
  85. package/std/matrix.js +5 -5
  86. package/std/numeric.d.ts +2 -1
  87. package/std/numeric.js +47 -10
  88. package/std/typeOf.d.ts +31 -0
  89. package/std/typeOf.js +54 -0
  90. package/tgpu.d.ts +1 -1
  91. package/tgpu.js +1 -1
  92. package/tgpuBindGroupLayout.d.ts +6 -3
  93. package/tgpuBindGroupLayout.js +15 -2
  94. package/tgpuLogger.d.ts +3 -0
  95. package/tgpuLogger.js +3 -0
  96. package/tgpuUnstableNamespace.d.ts +1 -0
  97. package/tgpuUnstableNamespace.js +5 -0
  98. package/tgsl/accessIndex.js +10 -7
  99. package/tgsl/accessProp.js +5 -57
  100. package/tgsl/consoleLog/serializers.d.ts +1 -8
  101. package/tgsl/consoleLog/serializers.js +53 -37
  102. package/tgsl/consoleLog/types.d.ts +1 -1
  103. package/tgsl/conversion.js +21 -0
  104. package/tgsl/forOfUtils.js +1 -1
  105. package/tgsl/generationHelpers.d.ts +0 -1
  106. package/tgsl/generationHelpers.js +1 -4
  107. package/tgsl/shaderGenerator.d.ts +5 -0
  108. package/tgsl/shellless.js +3 -20
  109. package/tgsl/swizzle.d.ts +24 -0
  110. package/tgsl/swizzle.js +112 -0
  111. package/tgsl/wgslGenerator.d.ts +13 -3
  112. package/tgsl/wgslGenerator.js +150 -152
  113. package/types.d.ts +10 -10
  114. package/types.js +1 -1
  115. package/unwrapper.d.ts +2 -2
  116. package/data/deepEqual.d.ts +0 -21
  117. package/data/deepEqual.js +0 -93
  118. package/taskQueue.d.ts +0 -6
  119. package/taskQueue.js +0 -30
@@ -0,0 +1,33 @@
1
+ import type { TgpuRoot } from '../core/root/rootTypes.ts';
2
+ export interface AttachAutoResizerOptions {
3
+ root: TgpuRoot;
4
+ canvas: HTMLCanvasElement;
5
+ onResize?: (() => void) | undefined;
6
+ }
7
+ export interface AutoResizer {
8
+ detach: () => void;
9
+ }
10
+ /**
11
+ * Keeps the canvas' internal resolution (`canvas.width` and `canvas.height`) in sync with
12
+ * the physical size it takes up on the screen. The resolution is clamped to what the
13
+ * device supports.
14
+ *
15
+ * @param options.onResize Called right after the canvas has been resized. Changing the canvas
16
+ * resolution clears its contents, so this is a good place to re-render the frame, and to
17
+ * resize any resolution-dependent resources.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const autoResizer = common.attachAutoResizer({
22
+ * root,
23
+ * canvas,
24
+ * onResize() {
25
+ * render();
26
+ * },
27
+ * });
28
+ *
29
+ * // Later, when the canvas is no longer used
30
+ * autoResizer.detach();
31
+ * ```
32
+ */
33
+ export declare function attachAutoResizer({ root, canvas, onResize, }: AttachAutoResizerOptions): AutoResizer;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Returns the physical (device pixel) size of the observed element, falling back to
3
+ * the CSS size multiplied by the device pixel ratio when the browser does not report it.
4
+ */
5
+ function getPhysicalSize(entry) {
6
+ // Not every browser supports `devicePixelContentBoxSize` (e.g. Safari), despite what the types say.
7
+ const dpcb = entry.devicePixelContentBoxSize?.[0];
8
+ if (dpcb) {
9
+ return [dpcb.inlineSize, dpcb.blockSize];
10
+ }
11
+ const dpr = window.devicePixelRatio || 1;
12
+ // Older browsers expose `contentBoxSize` as a single object instead of an array.
13
+ const contentBoxSize = entry.contentBoxSize;
14
+ const cb = Array.isArray(contentBoxSize)
15
+ ? contentBoxSize[0]
16
+ : contentBoxSize;
17
+ if (cb) {
18
+ return [cb.inlineSize * dpr, cb.blockSize * dpr];
19
+ }
20
+ return [entry.contentRect.width * dpr, entry.contentRect.height * dpr];
21
+ }
22
+ function getMaxCanvasSize(root) {
23
+ try {
24
+ return root.device.limits.maxTextureDimension2D;
25
+ }
26
+ catch {
27
+ // Roots that are not backed by a WebGPU device (e.g. the WebGL fallback) don't expose
28
+ // device limits. Falling back to the minimum value guaranteed by WebGPU.
29
+ return 8192;
30
+ }
31
+ }
32
+ /**
33
+ * Keeps the canvas' internal resolution (`canvas.width` and `canvas.height`) in sync with
34
+ * the physical size it takes up on the screen. The resolution is clamped to what the
35
+ * device supports.
36
+ *
37
+ * @param options.onResize Called right after the canvas has been resized. Changing the canvas
38
+ * resolution clears its contents, so this is a good place to re-render the frame, and to
39
+ * resize any resolution-dependent resources.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const autoResizer = common.attachAutoResizer({
44
+ * root,
45
+ * canvas,
46
+ * onResize() {
47
+ * render();
48
+ * },
49
+ * });
50
+ *
51
+ * // Later, when the canvas is no longer used
52
+ * autoResizer.detach();
53
+ * ```
54
+ */
55
+ export function attachAutoResizer({ root, canvas, onResize, }) {
56
+ const maxSize = getMaxCanvasSize(root);
57
+ const observer = new ResizeObserver((entries) => {
58
+ for (const entry of entries) {
59
+ const [width, height] = getPhysicalSize(entry);
60
+ const target = entry.target;
61
+ target.width = Math.max(1, Math.min(Math.round(width), maxSize));
62
+ target.height = Math.max(1, Math.min(Math.round(height), maxSize));
63
+ onResize?.();
64
+ }
65
+ });
66
+ try {
67
+ observer.observe(canvas, { box: 'device-pixel-content-box' });
68
+ }
69
+ catch {
70
+ try {
71
+ observer.observe(canvas, { box: 'content-box' });
72
+ }
73
+ catch {
74
+ // The `box` option is not supported at all
75
+ observer.observe(canvas);
76
+ }
77
+ }
78
+ return {
79
+ detach: () => {
80
+ observer.disconnect();
81
+ },
82
+ };
83
+ }
package/common/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { fullScreenTriangle } from './fullScreenTriangle.ts';
2
2
  export { writeChannels } from './writeChannels.ts';
3
+ export { attachAutoResizer, type AutoResizer, type AttachAutoResizerOptions, } from './attachAutoResizer.ts';
3
4
  export { writeSoA } from './writeSoA.ts';
package/common/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // NOTE: This is a barrel file, internal files should not import things from this file
2
2
  export { fullScreenTriangle } from "./fullScreenTriangle.js";
3
3
  export { writeChannels } from "./writeChannels.js";
4
+ export { attachAutoResizer, } from "./attachAutoResizer.js";
4
5
  export { writeSoA } from "./writeSoA.js";
@@ -4,6 +4,7 @@ import { alignmentOf } from "../data/alignmentOf.js";
4
4
  import { undecorate } from "../data/dataTypes.js";
5
5
  import { offsetsForProps } from "../data/offsets.js";
6
6
  import { sizeOf } from "../data/sizeOf.js";
7
+ import { strideOf } from "../data/schemaMemoryLayout.js";
7
8
  import { isAtomic, isMat, isMat2x2f, isMat3x3f, isWgslArray } from "../data/wgslTypes.js";
8
9
  import { getName } from "../shared/meta.js";
9
10
  function packedSchemaOf(schema) {
@@ -44,7 +45,7 @@ function computeSoAByteLength(arraySchema, soaData) {
44
45
  if (inferredCount === undefined) {
45
46
  return undefined;
46
47
  }
47
- const elementStride = roundUp(sizeOf(structSchema), alignmentOf(structSchema));
48
+ const elementStride = strideOf(arraySchema);
48
49
  return inferredCount * elementStride;
49
50
  }
50
51
  function writePackedValue(target, schema, srcBytes, dstOffset, srcOffset) {
@@ -61,7 +62,7 @@ function writePackedValue(target, schema, srcBytes, dstOffset, srcOffset) {
61
62
  }
62
63
  if (isWgslArray(unpackedSchema)) {
63
64
  const packedElementSize = packedSizeOf(unpackedSchema.elementType);
64
- const gpuElementStride = roundUp(sizeOf(unpackedSchema.elementType), alignmentOf(unpackedSchema.elementType));
65
+ const gpuElementStride = strideOf(unpackedSchema);
65
66
  for (let i = 0; i < unpackedSchema.elementCount; i++) {
66
67
  writePackedValue(target, unpackedSchema.elementType, srcBytes, dstOffset + i * gpuElementStride, srcOffset + i * packedElementSize);
67
68
  }
@@ -71,7 +72,7 @@ function writePackedValue(target, schema, srcBytes, dstOffset, srcOffset) {
71
72
  }
72
73
  function scatterSoA(target, arraySchema, soaData, startOffset, endOffset) {
73
74
  const structSchema = arraySchema.elementType;
74
- const elementStride = roundUp(sizeOf(structSchema), alignmentOf(structSchema));
75
+ const elementStride = strideOf(arraySchema);
75
76
  invariant(startOffset % elementStride === 0, `startOffset (${startOffset}) must be aligned to the element stride (${elementStride})`);
76
77
  const startElement = Math.floor(startOffset / elementStride);
77
78
  const endElement = Math.min(arraySchema.elementCount, Math.ceil(endOffset / elementStride));
@@ -18,7 +18,7 @@ export interface CommandEncoderInternals {
18
18
  *
19
19
  * @example
20
20
  * ```ts
21
- * const encoder = root['~unstable'].createCommandEncoder();
21
+ * const encoder = root.createCommandEncoder();
22
22
  * const pass = encoder.beginRenderPass({
23
23
  * colorAttachments: [{ view: msaaTexture, resolveTarget: context }],
24
24
  * });
@@ -1,12 +1,15 @@
1
- import { type ResolvedSnippet } from '../../data/snippet.ts';
2
- import { $internal, $resolve } from '../../shared/symbols.ts';
3
- import type { ResolutionCtx, SelfResolvable } from '../../types.ts';
1
+ import { Void } from '../../data/wgslTypes.ts';
2
+ import { $gpuValueOf, $internal } from '../../shared/symbols.ts';
3
+ import type { InferGPU } from '../../data/index.ts';
4
4
  /**
5
5
  * Extra declaration that shall be included in final WGSL code,
6
6
  * when resolving objects that use it.
7
7
  */
8
8
  export interface TgpuDeclare {
9
+ readonly [$internal]: true;
9
10
  $uses(dependencyMap: Record<string, unknown>): this;
11
+ readonly $: InferGPU<Void>;
12
+ readonly [$gpuValueOf]: InferGPU<Void>;
10
13
  }
11
14
  /**
12
15
  * Allows defining extra declarations that shall be included in the final WGSL code,
@@ -16,11 +19,11 @@ export interface TgpuDeclare {
16
19
  * It was developed to ensure full compatibility of TypeGPU programs with current and future versions of WGSL.
17
20
  */
18
21
  export declare function declare(declaration: string): TgpuDeclare;
19
- export declare class TgpuDeclareImpl implements TgpuDeclare, SelfResolvable {
22
+ export declare class TgpuDeclareImpl implements TgpuDeclare {
20
23
  #private;
21
- readonly [$internal] = true;
22
24
  constructor(declaration: string);
25
+ [$internal]: true;
26
+ $: InferGPU<Void>;
27
+ readonly [$gpuValueOf]: InferGPU<Void>;
23
28
  $uses(dependencyMap: Record<string, unknown>): this;
24
- [$resolve](ctx: ResolutionCtx): ResolvedSnippet;
25
- toString(): string;
26
29
  }
@@ -1,7 +1,9 @@
1
1
  import { snip } from "../../data/snippet.js";
2
2
  import { Void } from "../../data/wgslTypes.js";
3
- import { $internal, $resolve } from "../../shared/symbols.js";
3
+ import { $gpuValueOf, $internal } from "../../shared/symbols.js";
4
4
  import { replaceExternalsInWgsl } from "../resolve/externals.js";
5
+ import { makeDereferenceable } from "../../tgsl/makeDereferenceable.js";
6
+ import { makeResolvable } from "../../tgsl/makeResolvable.js";
5
7
  /**
6
8
  * Allows defining extra declarations that shall be included in the final WGSL code,
7
9
  * when resolving objects that use them.
@@ -16,12 +18,33 @@ export function declare(declaration) {
16
18
  // Implementation
17
19
  // --------------
18
20
  export class TgpuDeclareImpl {
19
- [$internal] = true;
20
21
  #externals;
21
22
  #declaration;
22
23
  constructor(declaration) {
23
24
  this.#declaration = declaration;
24
25
  }
26
+ static {
27
+ TgpuDeclareImpl.prototype[$internal] = true;
28
+ makeDereferenceable(makeResolvable(TgpuDeclareImpl.prototype, {
29
+ asString() {
30
+ return `declare: ${this.#declaration}`;
31
+ },
32
+ resolve(ctx) {
33
+ const replacedDeclaration = replaceExternalsInWgsl(ctx, this.#externals ?? {}, this.#declaration);
34
+ ctx.addDeclaration(replacedDeclaration);
35
+ return snip('', Void, /* origin */ 'constant');
36
+ },
37
+ }), {
38
+ codegenMode: {
39
+ getBaseSnippet(trackingProxy) {
40
+ return snip(trackingProxy, Void,
41
+ /* origin */ 'constant',
42
+ /* possibleSideEffects */ false);
43
+ },
44
+ },
45
+ normalMode: { get() { } },
46
+ });
47
+ }
25
48
  $uses(dependencyMap) {
26
49
  if (this.#externals !== undefined) {
27
50
  throw new Error("Cannot call '$uses' multiple times. If you wish to override dependencies, use slots or accessors instead.");
@@ -29,12 +52,4 @@ export class TgpuDeclareImpl {
29
52
  this.#externals = dependencyMap;
30
53
  return this;
31
54
  }
32
- [$resolve](ctx) {
33
- const replacedDeclaration = replaceExternalsInWgsl(ctx, this.#externals ?? {}, this.#declaration);
34
- ctx.addDeclaration(replacedDeclaration);
35
- return snip('', Void, /* origin */ 'constant');
36
- }
37
- toString() {
38
- return `declare: ${this.#declaration}`;
39
- }
40
55
  }
@@ -3,9 +3,11 @@ import { $getNameForward, $internal } from '../../shared/symbols.ts';
3
3
  import { type DualFn } from '../../types.ts';
4
4
  type AnyFn = (...args: never[]) => unknown;
5
5
  export type TgpuComptime<T extends AnyFn = AnyFn> = DualFn<T> & TgpuNamable & {
6
+ toString(): string;
6
7
  [$getNameForward]: unknown;
7
8
  [$internal]: {
8
9
  isComptime: true;
10
+ func: T;
9
11
  };
10
12
  };
11
13
  export declare function isComptimeFn(value: unknown): value is TgpuComptime;
@@ -35,32 +35,37 @@ export function comptime(func) {
35
35
  const impl = ((...args) => {
36
36
  return func(...args);
37
37
  });
38
- impl.toString = () => 'comptime';
38
+ Object.setPrototypeOf(impl, ComptimePrototype);
39
39
  impl[$getNameForward] = func;
40
- impl[$gpuCallable] = {
41
- call(ctx, args) {
42
- const comptimeArgs = args.map((s) => asComptime(s));
43
- if (!comptimeArgs.every((s) => s !== undefined)) {
44
- throw new WgslTypeError(`Called comptime function with runtime-known values: ${args
45
- .filter((_, idx) => comptimeArgs[idx] === undefined)
46
- .map((s) => `'${stringifySnippet(s)}'`)
47
- .join(', ')}`);
48
- }
49
- ctx.pushMode(new NormalState());
50
- try {
51
- return coerceToSnippet(func(...comptimeArgs.map((s) => s.value)));
52
- }
53
- finally {
54
- ctx.popMode();
55
- }
56
- },
57
- };
58
- impl.$name = (label) => {
59
- setName(func, label);
60
- return impl;
61
- };
62
40
  Object.defineProperty(impl, $internal, {
63
- value: { isComptime: true },
41
+ value: { isComptime: true, func },
64
42
  });
65
43
  return impl;
66
44
  }
45
+ const ComptimePrototype = {
46
+ toString() {
47
+ return 'comptime';
48
+ },
49
+ $name(label) {
50
+ setName(this[$internal].func, label);
51
+ return this;
52
+ },
53
+ [$gpuCallable](ctx, args) {
54
+ const comptimeArgs = args.map((s) => asComptime(s));
55
+ if (!comptimeArgs.every((s) => s !== undefined)) {
56
+ throw new WgslTypeError(`Called comptime function with runtime-known values: ${args
57
+ .filter((_, idx) => comptimeArgs[idx] === undefined)
58
+ .map((s) => `'${stringifySnippet(s)}'`)
59
+ .join(', ')}`);
60
+ }
61
+ ctx.pushMode(new NormalState());
62
+ try {
63
+ return coerceToSnippet(this[$internal].func.apply(undefined, comptimeArgs.map((s) => s.value)));
64
+ }
65
+ finally {
66
+ ctx.popMode();
67
+ }
68
+ },
69
+ };
70
+ // Comptime functions are still functions, so they should keep `call`, `apply`, `bind`, etc.
71
+ Object.setPrototypeOf(ComptimePrototype, Function.prototype);
@@ -10,46 +10,41 @@ export function callableSchema(options) {
10
10
  });
11
11
  setName(impl, options.name);
12
12
  impl.toString = () => options.name;
13
- impl[$gpuCallable] = {
14
- get strictSignature() {
15
- return undefined;
16
- },
17
- call(ctx, args) {
18
- const argTypes = options.argTypes(...args.map((s) => {
19
- // Dereference implicit pointers
20
- if (isPtr(s.dataType) && s.dataType.implicit) {
21
- return s.dataType.inner;
22
- }
23
- return s.dataType;
24
- }));
25
- const converted = args.map((s, idx) => {
26
- const argType = argTypes[idx];
27
- if (!argType) {
28
- throw new Error('Function called with invalid arguments');
29
- }
30
- return tryConvertSnippet(ctx, s, argType, false);
31
- });
32
- let result;
33
- const comptimeArgs = converted.map((s) => asComptime(s));
34
- if (comptimeArgs.every((s) => s !== undefined)) {
35
- ctx.pushMode(new NormalState());
36
- try {
37
- result = snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), options.schema(),
38
- // Functions give up ownership of their return value
39
- /* origin */ 'constant');
40
- }
41
- finally {
42
- ctx.popMode('normal');
43
- }
13
+ impl[$gpuCallable] = (ctx, args) => {
14
+ const argTypes = options.argTypes(...args.map((s) => {
15
+ // Dereference implicit pointers
16
+ if (isPtr(s.dataType) && s.dataType.implicit) {
17
+ return s.dataType.inner;
44
18
  }
45
- else {
46
- result = options.codegenImpl(ctx, converted);
19
+ return s.dataType;
20
+ }));
21
+ const converted = args.map((s, idx) => {
22
+ const argType = argTypes[idx];
23
+ if (!argType) {
24
+ throw new Error('Function called with invalid arguments');
47
25
  }
48
- if (!args.some((a) => a.possibleSideEffects)) {
49
- return noSideEffects(result);
26
+ return tryConvertSnippet(ctx, s, argType, false);
27
+ });
28
+ let result;
29
+ const comptimeArgs = converted.map((s) => asComptime(s));
30
+ if (comptimeArgs.every((s) => s !== undefined)) {
31
+ ctx.pushMode(new NormalState());
32
+ try {
33
+ result = snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), options.schema(),
34
+ // Functions give up ownership of their return value
35
+ /* origin */ 'constant');
50
36
  }
51
- return result;
52
- },
37
+ finally {
38
+ ctx.popMode('normal');
39
+ }
40
+ }
41
+ else {
42
+ result = options.codegenImpl(ctx, converted);
43
+ }
44
+ if (!args.some((a) => a.possibleSideEffects)) {
45
+ return noSideEffects(result);
46
+ }
47
+ return result;
53
48
  };
54
49
  return impl;
55
50
  }
@@ -1,6 +1,6 @@
1
1
  import { snip } from "../../data/snippet.js";
2
2
  import { setName } from "../../shared/meta.js";
3
- import { $gpuCallable } from "../../shared/symbols.js";
3
+ import { $gpuCallable, $gpuCallableStrictSignature } from "../../shared/symbols.js";
4
4
  import { tryConvertSnippet } from "../../tgsl/conversion.js";
5
5
  import { concretize } from "../../tgsl/generationHelpers.js";
6
6
  import { asComptime, NormalState } from "../../types.js";
@@ -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') {
@@ -22,55 +23,55 @@ export function dualImpl(options) {
22
23
  setName(impl, options.name);
23
24
  }
24
25
  impl.toString = () => options.name ?? '<unknown>';
25
- impl[$gpuCallable] = {
26
- get strictSignature() {
26
+ Object.defineProperty(impl, $gpuCallableStrictSignature, {
27
+ get() {
27
28
  return typeof options.signature !== 'function' ? options.signature : undefined;
28
29
  },
29
- call(ctx, args) {
30
- const { argTypes, returnType } = typeof options.signature === 'function'
31
- ? options.signature(...args.map((s) => {
32
- // Dereference implicit pointers
33
- if (isPtr(s.dataType) && s.dataType.implicit) {
34
- return s.dataType.inner;
35
- }
36
- return s.dataType;
37
- }))
38
- : options.signature;
39
- const converted = args.map((s, idx) => {
40
- const argType = argTypes[idx];
41
- if (!argType) {
42
- throw new Error('Function called with invalid arguments');
30
+ });
31
+ impl[$gpuCallable] = (ctx, args) => {
32
+ const { argTypes, returnType } = typeof options.signature === 'function'
33
+ ? options.signature(...args.map((s) => {
34
+ // Dereference implicit pointers
35
+ if (isPtr(s.dataType) && s.dataType.implicit) {
36
+ return s.dataType.inner;
43
37
  }
44
- return tryConvertSnippet(ctx, s, argType, !options.ignoreImplicitCastWarning);
45
- });
46
- if (!options.noComptime && typeof options.normalImpl === 'function') {
47
- const comptimeArgs = converted.map((s) => asComptime(s));
48
- if (comptimeArgs.every((s) => s !== undefined)) {
49
- ctx.pushMode(new NormalState());
50
- try {
51
- return snip(options.normalImpl(...comptimeArgs.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;
61
- }
62
- }
63
- finally {
64
- ctx.popMode('normal');
38
+ return s.dataType;
39
+ }))
40
+ : options.signature;
41
+ const converted = args.map((s, idx) => {
42
+ const argType = argTypes[idx];
43
+ if (!argType) {
44
+ throw new Error('Function called with invalid arguments');
45
+ }
46
+ return tryConvertSnippet(ctx, s, argType, !options.ignoreImplicitCastWarning);
47
+ });
48
+ if (!options.noComptime && typeof options.normalImpl === 'function') {
49
+ const comptimeArgs = converted.map((s) => asComptime(s));
50
+ if (comptimeArgs.every((s) => s !== undefined)) {
51
+ ctx.pushMode(new NormalState());
52
+ try {
53
+ return snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), returnType,
54
+ // Functions give up ownership of their return value
55
+ /* origin */ 'constant', options.sideEffects);
56
+ }
57
+ catch (e) {
58
+ // cpuImpl may in some cases be present but implemented only partially.
59
+ // In that case, if the MissingCpuImplError is thrown, we fallback to codegenImpl.
60
+ // If it is any other error, we just rethrow.
61
+ if (!(e instanceof MissingCpuImplError)) {
62
+ throw e;
65
63
  }
66
64
  }
65
+ finally {
66
+ ctx.popMode('normal');
67
+ }
67
68
  }
68
- const possibleSideEffects = options.sideEffects || args.some((a) => a.possibleSideEffects);
69
- const concreteReturnType = concretize(returnType);
70
- return snip(options.codegenImpl(ctx, converted, concreteReturnType), concreteReturnType,
71
- // Functions give up ownership of their return value
72
- /* origin */ 'runtime', possibleSideEffects);
73
- },
69
+ }
70
+ const possibleSideEffects = options.sideEffects || args.some((a) => a.possibleSideEffects);
71
+ const concreteReturnType = concretize(returnType);
72
+ return snip(options.codegenImpl(ctx, converted, concreteReturnType), concreteReturnType,
73
+ // Functions give up ownership of their return value
74
+ /* origin */ 'runtime', possibleSideEffects);
74
75
  };
75
76
  return impl;
76
77
  }
@@ -33,9 +33,6 @@ export interface TgpuComputeFn<ComputeIn extends IORecord<AnyComputeBuiltin> = a
33
33
  readonly shell: TgpuComputeFnShellHeader<ComputeIn>;
34
34
  $uses(dependencyMap: Record<string, unknown>): this;
35
35
  }
36
- export interface ComputeFnOptions {
37
- workgroupSize: number[];
38
- }
39
36
  export declare function computeFn(options: {
40
37
  workgroupSize: number[];
41
38
  }): TgpuComputeFnShell<{}>;
@@ -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>> {
@@ -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";
@@ -27,12 +28,12 @@ export function fn(argTypesOrCallback, returnType) {
27
28
  return Object.assign(call, shell);
28
29
  }
29
30
  export function isTgpuFn(value) {
30
- return (isMarkedInternal(value) &&
31
- value?.resourceType === 'function');
31
+ return (value?.resourceType === 'function' &&
32
+ isMarkedInternal(value));
32
33
  }
33
34
  export function isGenericFn(value) {
34
- return (isMarkedInternal(value) &&
35
- value?.resourceType === 'generic-function');
35
+ return (value?.resourceType === 'generic-function' &&
36
+ isMarkedInternal(value));
36
37
  }
37
38
  // --------------
38
39
  // Implementation
@@ -44,6 +45,15 @@ function bindingsOf(transform) {
44
45
  return transform(new ConfigurableImpl([])).bindings;
45
46
  }
46
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
+ }
47
57
  let pairs = [];
48
58
  // Unwrapping generic functions
49
59
  let implementation;
@@ -47,7 +47,7 @@ export interface TgpuFragmentFnShell<out TIn extends TgpuFragmentFn.In = TgpuFra
47
47
  (implementation: string): TgpuFragmentFn<CleanIO<TIn>, CleanIO<TOut>>;
48
48
  (strings: TemplateStringsArray, ...values: unknown[]): TgpuFragmentFn<CleanIO<TIn>, CleanIO<TOut>>;
49
49
  }
50
- export interface TgpuFragmentFn<in Varying extends TgpuFragmentFn.In = Record<string, never>, out Output extends TgpuFragmentFn.Out = TgpuFragmentFn.Out> extends TgpuNamable {
50
+ export interface TgpuFragmentFn<in Varying extends TgpuFragmentFn.In = never, out Output extends TgpuFragmentFn.Out = TgpuFragmentFn.Out> extends TgpuNamable {
51
51
  readonly [$internal]: true;
52
52
  readonly shell: TgpuFragmentFnShellHeader<Varying, Output>;
53
53
  readonly outputType: IOLayoutToSchema<Output>;
@@ -33,7 +33,7 @@ export interface TgpuVertexFnShell<out TIn extends TgpuVertexFn.In, out TOut ext
33
33
  (implementation: string): TgpuVertexFn<CleanIO<TIn>, CleanIO<TOut>>;
34
34
  (strings: TemplateStringsArray, ...values: unknown[]): TgpuVertexFn<CleanIO<TIn>, CleanIO<TOut>>;
35
35
  }
36
- export interface TgpuVertexFn<in VertexIn extends TgpuVertexFn.In = Record<string, never>, out VertexOut extends TgpuVertexFn.Out = TgpuVertexFn.Out> extends TgpuNamable {
36
+ export interface TgpuVertexFn<in VertexIn extends TgpuVertexFn.In = never, out VertexOut extends TgpuVertexFn.Out = TgpuVertexFn.Out> extends TgpuNamable {
37
37
  readonly [$internal]: true;
38
38
  readonly shell: TgpuVertexFnShellHeader<VertexIn, VertexOut>;
39
39
  $uses(dependencyMap: Record<string, unknown>): this;
@@ -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);