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,131 @@
1
+ import { comptime } from "../core/function/comptime.js";
2
+ import { isDisarray, isLooseDecorated, isUnstruct } from "./dataTypes.js";
3
+ import { isWgslStorageTexture, isWgslTexture } from "./texture.js";
4
+ import { isAtomic, isDecorated, isPtr, isWgslArray, isWgslStruct } from "./wgslTypes.js";
5
+ /**
6
+ * Performs a structural comparison of two TypeGPU data schemas. This
7
+ * means two struct definitions are considered equal when they have the
8
+ * same properties. Use `schemasEqualNominally` for a nominal comparison.
9
+ *
10
+ * @param a The first data schema to compare.
11
+ * @param b The second data schema to compare.
12
+ * @returns `true` if the schemas are structurally equal, `false` otherwise.
13
+ *
14
+ * @example
15
+ * import { vec3f, struct, schemasEqualStructurally } from 'typegpu/data';
16
+ *
17
+ * console.log(schemasEqualStructurally(struct({ a: vec3f }), struct({ a: vec3f }))); // true
18
+ * console.log(schemasEqualStructurally(struct({ a: vec3f }), struct({ b: vec3f }))); // false
19
+ */
20
+ export const schemasEqualStructurally = comptime((a, b) => schemasEqual(a, b, true)).$name('schemasEqualStructurally');
21
+ /**
22
+ * Performs a nominal comparison of two TypeGPU data schemas. This
23
+ * means two struct definitions are only considered equal when they
24
+ * have the same object identity. Use `schemasEqualStructurally` for
25
+ * a structural comparison.
26
+ *
27
+ * @param a The first data schema to compare.
28
+ * @param b The second data schema to compare.
29
+ * @returns `true` if the schemas are nominally equal, `false` otherwise.
30
+ *
31
+ * @example
32
+ * import { vec3f, struct, schemasEqualNominally } from 'typegpu/data';
33
+ *
34
+ * const struct1 = struct({ a: vec3f });
35
+ * const struct2 = struct({ a: vec3f });
36
+ *
37
+ * console.log(schemasEqualNominally(d.arrayOf(struct1, 2), d.arrayOf(struct1, 2))); // true
38
+ * console.log(schemasEqualNominally(struct1, struct2)); // false
39
+ */
40
+ export const schemasEqualNominally = comptime((a, b) => schemasEqual(a, b, false)).$name('schemasEqualNominally');
41
+ function schemasEqual(a, b, structural) {
42
+ if (a === b) {
43
+ return true;
44
+ }
45
+ if (a.type !== b.type) {
46
+ return false;
47
+ }
48
+ if ((isWgslStruct(a) && isWgslStruct(b)) || (isUnstruct(a) && isUnstruct(b))) {
49
+ if (!structural) {
50
+ // With nominal typing, structs are only considered equal when they
51
+ // generate the same declaration, i.e. have the same object identity.
52
+ // If they didn't pass the previous condition, then they're not equal
53
+ return false;
54
+ }
55
+ const aProps = a.propTypes;
56
+ const bProps = b.propTypes;
57
+ const aKeys = Object.keys(aProps);
58
+ const bKeys = Object.keys(bProps);
59
+ if (aKeys.length !== bKeys.length) {
60
+ return false;
61
+ }
62
+ for (let i = 0; i < aKeys.length; i++) {
63
+ const keyA = aKeys[i];
64
+ const keyB = bKeys[i];
65
+ if (keyA !== keyB ||
66
+ !keyA ||
67
+ !keyB ||
68
+ !schemasEqual(aProps[keyA], bProps[keyB], structural)) {
69
+ return false;
70
+ }
71
+ }
72
+ return true;
73
+ }
74
+ if ((isWgslArray(a) && isWgslArray(b)) || (isDisarray(a) && isDisarray(b))) {
75
+ return (a.elementCount === b.elementCount &&
76
+ schemasEqual(a.elementType, b.elementType, structural));
77
+ }
78
+ if (isPtr(a) && isPtr(b)) {
79
+ return (a.addressSpace === b.addressSpace &&
80
+ a.access === b.access &&
81
+ a.implicit === b.implicit &&
82
+ schemasEqual(a.inner, b.inner, structural));
83
+ }
84
+ if (isAtomic(a) && isAtomic(b)) {
85
+ return schemasEqual(a.inner, b.inner, structural);
86
+ }
87
+ if (isWgslTexture(a) && isWgslTexture(b)) {
88
+ // Dimension and multisampling are already encoded in the type
89
+ return schemasEqual(a.sampleType, b.sampleType, structural);
90
+ }
91
+ if (isWgslStorageTexture(a) && isWgslStorageTexture(b)) {
92
+ // Dimension is already encoded in the type
93
+ return a.format === b.format && a.access === b.access;
94
+ }
95
+ if ((isDecorated(a) && isDecorated(b)) || (isLooseDecorated(a) && isLooseDecorated(b))) {
96
+ if (!schemasEqual(a.inner, b.inner, structural)) {
97
+ return false;
98
+ }
99
+ // Attribute order carries no meaning, so we compare attributes by type.
100
+ // Only the first (outermost) attribute of each type is effective.
101
+ const attribsA = effectiveAttribs(a.attribs);
102
+ const attribsB = effectiveAttribs(b.attribs);
103
+ if (attribsA.size !== attribsB.size) {
104
+ return false;
105
+ }
106
+ for (const [type, attrA] of attribsA) {
107
+ const attrB = attribsB.get(type);
108
+ if (!attrB) {
109
+ return false;
110
+ }
111
+ const paramsA = attrA.params ?? [];
112
+ const paramsB = attrB.params ?? [];
113
+ if (paramsA.length !== paramsB.length ||
114
+ paramsA.some((param, idx) => param !== paramsB[idx])) {
115
+ return false;
116
+ }
117
+ }
118
+ return true;
119
+ }
120
+ // All other types have been checked for equality at the start
121
+ return true;
122
+ }
123
+ function effectiveAttribs(attribs) {
124
+ const result = new Map();
125
+ for (const attrib of attribs) {
126
+ if (!result.has(attrib.type)) {
127
+ result.set(attrib.type, attrib);
128
+ }
129
+ }
130
+ return result;
131
+ }
package/data/snippet.d.ts CHANGED
@@ -62,7 +62,14 @@ export declare const originToPtrParams: {
62
62
  };
63
63
  };
64
64
  export type OriginToPtrParams = typeof originToPtrParams;
65
+ /**
66
+ * Whether values of this origin can have their address taken.
67
+ */
65
68
  export declare function isAddressableOrigin(origin: Origin): origin is keyof OriginToPtrParams;
69
+ /**
70
+ * Whether values of this origin can be mutated.
71
+ */
72
+ export declare function isMutableOrigin(origin: Origin): boolean;
66
73
  export interface Snippet {
67
74
  readonly value: unknown;
68
75
  /**
package/data/snippet.js CHANGED
@@ -49,9 +49,18 @@ export const originToPtrParams = {
49
49
  // Local declarations are also in the `function` address space
50
50
  'local-def': { space: 'function', access: 'read-write' },
51
51
  };
52
+ /**
53
+ * Whether values of this origin can have their address taken.
54
+ */
52
55
  export function isAddressableOrigin(origin) {
53
56
  return origin in originToPtrParams;
54
57
  }
58
+ /**
59
+ * Whether values of this origin can be mutated.
60
+ */
61
+ export function isMutableOrigin(origin) {
62
+ return isAddressableOrigin(origin) && originToPtrParams[origin].access === 'read-write';
63
+ }
55
64
  class SnippetImpl {
56
65
  value;
57
66
  dataType;
package/data/struct.js CHANGED
@@ -16,9 +16,14 @@ import { schemaCallWrapper } from "./schemaCallWrapper.js";
16
16
  * @param props Record with `string` keys and `TgpuData` values,
17
17
  * each entry describing one struct member.
18
18
  */
19
+ /*#__NO_SIDE_EFFECTS__*/
19
20
  export function struct(props) {
21
+ if (Object.keys(props).length === 0) {
22
+ throw new Error('Cannot create struct schema with no properties.');
23
+ }
20
24
  return INTERNAL_createStruct(props, false);
21
25
  }
26
+ /*#__NO_SIDE_EFFECTS__*/
22
27
  export function abstruct(props) {
23
28
  return INTERNAL_createStruct(props, true);
24
29
  }
@@ -23,7 +23,7 @@ export interface NumberArrayView {
23
23
  /**
24
24
  * Maps a scalar, vector, or matrix element schema to the corresponding TypedArray type.
25
25
  */
26
- export type TypedArrayFor<T> = T extends F32 | Vec2f | Vec3f | Vec4f | Mat2x2f | Mat3x3f | Mat4x4f ? Float32Array : T extends F16 | Vec2h | Vec3h | Vec4h ? Float16Array : T extends I32 | Vec2i | Vec3i | Vec4i | Atomic<I32> ? Int32Array : T extends U32 | Vec2u | Vec3u | Vec4u | Atomic<U32> ? Uint32Array : T extends U16 ? Uint16Array : T extends Decorated<infer TBase> ? TypedArrayFor<TBase> : never;
26
+ export type TypedArrayFor<T> = T extends F32 | Vec2f | Vec3f | Vec4f | Mat2x2f | Mat3x3f | Mat4x4f ? Float32Array : T extends F16 | Vec2h | Vec3h | Vec4h ? Float16Array : T extends I32 | Vec2i | Vec3i | Vec4i | Atomic<I32> ? Int32Array : T extends U32 | Vec2u | Vec3u | Vec4u | Atomic<U32> ? Uint32Array : T extends U16 ? Uint16Array : T extends Decorated<infer TBase> ? TypedArrayFor<TBase> : T extends BaseData ? string extends T['type'] ? Float32Array | Float16Array | Int32Array | Uint32Array | Uint16Array : never : never;
27
27
  /**
28
28
  * Vector infix notation.
29
29
  *
@@ -704,7 +704,7 @@ export interface Mat2x2f extends BaseData {
704
704
  readonly type: 'mat2x2f';
705
705
  readonly primitive: F32;
706
706
  readonly [$repr]: m2x2f;
707
- readonly [$inRepr]: m2x2f | readonly number[] | Float32Array;
707
+ readonly [$inRepr]: m2x2f | readonly [number, number, number, number] | Float32Array;
708
708
  readonly [$validStorageSchema]: true;
709
709
  readonly [$validUniformSchema]: true;
710
710
  (...elements: [number, number, number, number]): m2x2f;
@@ -720,7 +720,7 @@ export interface Mat3x3f extends BaseData {
720
720
  readonly type: 'mat3x3f';
721
721
  readonly primitive: F32;
722
722
  readonly [$repr]: m3x3f;
723
- readonly [$inRepr]: m3x3f | readonly number[] | Float32Array;
723
+ readonly [$inRepr]: m3x3f | readonly [number, number, number, number, number, number, number, number, number] | Float32Array;
724
724
  readonly [$validStorageSchema]: true;
725
725
  readonly [$validUniformSchema]: true;
726
726
  (...elements: [number, number, number, number, number, number, number, number, number]): m3x3f;
@@ -736,7 +736,7 @@ export interface Mat4x4f extends BaseData {
736
736
  readonly type: 'mat4x4f';
737
737
  readonly primitive: F32;
738
738
  readonly [$repr]: m4x4f;
739
- readonly [$inRepr]: m4x4f | readonly number[] | Float32Array;
739
+ readonly [$inRepr]: m4x4f | readonly [number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number] | Float32Array;
740
740
  readonly [$validStorageSchema]: true;
741
741
  readonly [$validUniformSchema]: true;
742
742
  (...elements: [number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number]): m4x4f;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typegpu",
3
- "version": "0.12.7",
3
+ "version": "0.12.9",
4
4
  "description": "A thin layer between JS and WebGPU/WGSL that improves development experience and allows for faster iteration.",
5
5
  "keywords": [
6
6
  "compute",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "tsover-runtime": "^0.0.7",
52
- "typed-binary": "^4.3.3",
52
+ "typed-binary": "^4.3.4",
53
53
  "tinyest": "~0.3.4"
54
54
  },
55
55
  "engines": {
package/resolutionCtx.js CHANGED
@@ -417,7 +417,7 @@ export class ResolutionCtxImpl {
417
417
  return this._indentController.dedent();
418
418
  }
419
419
  getDedented(code) {
420
- return code.replaceAll(`\n${INDENT[1]}`, '\n');
420
+ return code.replaceAll(`\n${INDENT[1]}`, '\n').replaceAll(new RegExp(`^${INDENT[1]}`, 'g'), '');
421
421
  }
422
422
  withResetIndentLevel(callback) {
423
423
  return this._indentController.withResetLevel(callback);
@@ -9,7 +9,7 @@ import type { TgpuQuerySetSoul } from '../core/querySet/querySet.ts';
9
9
  import type { TgpuGuardedComputePipelineSoul, TgpuRootSoul } from '../core/root/rootTypes.ts';
10
10
  import type { TgpuSamplerSoul } from '../core/sampler/sampler.ts';
11
11
  import type { TgpuAccessorSoul, TgpuMutableAccessor, TgpuSlotSoul } from '../core/slot/slotTypes.ts';
12
- import { type TgpuTextureSoul } from '../core/texture/texture.ts';
12
+ import { INTERNAL_restoreTextureView, type TgpuTextureSoul, type TgpuTextureViewSoul } from '../core/texture/texture.ts';
13
13
  import { type TgpuVertexLayoutSoul } from '../core/vertexLayout/vertexLayout.ts';
14
14
  import type { AnyData } from '../data/dataTypes.ts';
15
15
  import { type AnyWgslData } from '../data/wgslTypes.ts';
@@ -18,7 +18,7 @@ import { type TgpuBindGroupLayoutSoul, type TgpuBindGroupSoul } from '../tgpuBin
18
18
  import type { TgpuSoul } from '../shared/soul.ts';
19
19
  import type { RestoreContext } from './types.ts';
20
20
  /** Every soul that can cross a device boundary, discriminated by `type` */
21
- export type TgpuResourceSoul = TgpuBufferSoul | TgpuBufferBindingSoul | TgpuTextureSoul | TgpuSamplerSoul | TgpuQuerySetSoul | TgpuBindGroupLayoutSoul | TgpuBindGroupSoul | TgpuVertexLayoutSoul | TgpuConstSoul | TgpuImmediateVarSoul | TgpuSlotSoul | TgpuAccessorSoul | TgpuComputePipelineSoul | TgpuRenderPipelineSoul | TgpuGuardedComputePipelineSoul | TgpuRootSoul;
21
+ export type TgpuResourceSoul = TgpuBufferSoul | TgpuBufferBindingSoul | TgpuTextureSoul | TgpuTextureViewSoul | TgpuSamplerSoul | TgpuQuerySetSoul | TgpuBindGroupLayoutSoul | TgpuBindGroupSoul | TgpuVertexLayoutSoul | TgpuConstSoul | TgpuImmediateVarSoul | TgpuSlotSoul | TgpuAccessorSoul | TgpuComputePipelineSoul | TgpuRenderPipelineSoul | TgpuGuardedComputePipelineSoul | TgpuRootSoul;
22
22
  type Restorer<TSoul extends TgpuSoul> = (soul: TSoul, ctx: RestoreContext) => unknown;
23
23
  declare function restoreBufferBinding(soul: TgpuBufferBindingSoul): TgpuBufferBindingImpl<"uniform" | "mutable" | "readonly", BaseData>;
24
24
  /**
@@ -31,6 +31,7 @@ export declare const soulRestorers: {
31
31
  mutable: typeof restoreBufferBinding;
32
32
  readonly: typeof restoreBufferBinding;
33
33
  texture: (soul: TgpuTextureSoul, ctx: RestoreContext) => import("../indexNamedExports.ts").TgpuTexture<TextureProps>;
34
+ 'texture-view': typeof INTERNAL_restoreTextureView;
34
35
  sampler: (soul: TgpuSamplerSoul, ctx: RestoreContext) => import("../indexNamedExports.ts").TgpuFixedSampler;
35
36
  'sampler-comparison': (soul: TgpuSamplerSoul, ctx: RestoreContext) => import("../indexNamedExports.ts").TgpuFixedComparisonSampler;
36
37
  'query-set': (soul: TgpuQuerySetSoul, ctx: RestoreContext) => import("../indexNamedExports.ts").TgpuQuerySet<GPUQueryType>;
package/serial/restore.js CHANGED
@@ -7,7 +7,7 @@ import { INTERNAL_restoreRenderPipeline, } from "../core/pipeline/renderPipeline
7
7
  import { INTERNAL_restoreGuardedComputePipeline, INTERNAL_restoreRoot } from "../core/root/init.js";
8
8
  import { accessor, mutableAccessor } from "../core/slot/accessor.js";
9
9
  import { slot } from "../core/slot/slot.js";
10
- import { INTERNAL_createTexture } from "../core/texture/texture.js";
10
+ import { INTERNAL_createTexture, INTERNAL_restoreTextureView, } from "../core/texture/texture.js";
11
11
  import { vertexLayout } from "../core/vertexLayout/vertexLayout.js";
12
12
  import { arrayOf } from "../data/array.js";
13
13
  import { disarrayOf } from "../data/disarray.js";
@@ -40,6 +40,7 @@ export const soulRestorers = {
40
40
  }
41
41
  return texture;
42
42
  },
43
+ 'texture-view': INTERNAL_restoreTextureView,
43
44
  sampler: (soul, ctx) => ctx.getRoot(soul.device).createSampler(soul.props),
44
45
  'sampler-comparison': (soul, ctx) => ctx.getRoot(soul.device).createComparisonSampler(soul.props),
45
46
  'query-set': (soul, ctx) => ctx.getRoot(soul.device).createQuerySet(soul.queryType, soul.count, soul.raw),
package/shared/meta.js CHANGED
@@ -1,4 +1,4 @@
1
- const version = "0.12.7";
1
+ const version = "0.12.9";
2
2
  import { DEV, TEST } from "./env.js";
3
3
  import { $getNameForward, $soul, isMarkedInternal } from "./symbols.js";
4
4
  import { normalizeMetadata } from "./normalizeMetadata.js";
@@ -18,6 +18,11 @@ export declare const $providing: unique symbol;
18
18
  * Objects can provide the snippet that represents them.
19
19
  */
20
20
  export declare const $ownSnippet: unique symbol;
21
+ /**
22
+ * Objects can provide the value that they represent at comptime (e.g. when passed
23
+ * into comptime functions), or signal that they are not known at comptime.
24
+ */
25
+ export declare const $comptimeValueOf: unique symbol;
21
26
  export declare const $resolve: unique symbol;
22
27
  /**
23
28
  * A way for a schema to provide casting behavior, without the need to be explicitly
package/shared/symbols.js CHANGED
@@ -1,4 +1,4 @@
1
- const version = "0.12.7";
1
+ const version = "0.12.9";
2
2
  export const $internal = Symbol(`typegpu:${version}:$internal`);
3
3
  /** A plain record of all definitional state of a resource, surviving transfer between runtimes */
4
4
  export const $soul = Symbol(`typegpu:${version}:$soul`);
@@ -19,6 +19,11 @@ export const $providing = Symbol(`typegpu:${version}:$providing`);
19
19
  * Objects can provide the snippet that represents them.
20
20
  */
21
21
  export const $ownSnippet = Symbol(`typegpu:${version}:$ownSnippet`);
22
+ /**
23
+ * Objects can provide the value that they represent at comptime (e.g. when passed
24
+ * into comptime functions), or signal that they are not known at comptime.
25
+ */
26
+ export const $comptimeValueOf = Symbol(`typegpu:${version}:$comptimeValueOf`);
22
27
  export const $resolve = Symbol(`typegpu:${version}:$resolve`);
23
28
  /**
24
29
  * A way for a schema to provide casting behavior, without the need to be explicitly
@@ -0,0 +1,67 @@
1
+ import { type DualFn } from '../types.ts';
2
+ /**
3
+ * Returns `true` if the value passed into it is statically known at comptime (during shader
4
+ * generation), and `false` if the value is determined by shader execution.
5
+ * During normal JavaScript execution every value is available right away, so it always
6
+ * returns `true`.
7
+ *
8
+ * Note that shader constants are NOT considered statically known at comptime, therefore
9
+ * `isKnownAtComptime()` returns `false` for them.
10
+ *
11
+ * A good example of where this is useful is opting into optimizations that are
12
+ * only valid when a value is statically known, like unrolling a loop whose iteration count
13
+ * depends on the size of an array:
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const layout = tgpu.bindGroupLayout({
18
+ * // Swapping this for `d.arrayOf(d.vec2f)` (a runtime-sized array)
19
+ * // makes the loop below stay a loop.
20
+ * boids: { storage: d.arrayOf(d.vec2f, 3) },
21
+ * });
22
+ *
23
+ * function centroid() {
24
+ * 'use gpu';
25
+ * let sum = d.vec2f();
26
+ *
27
+ * for (
28
+ * const boid of std.isKnownAtComptime(layout.$.boids.length)
29
+ * ? tgpu.unroll(layout.$.boids)
30
+ * : layout.$.boids
31
+ * ) {
32
+ * sum += boid;
33
+ * }
34
+ *
35
+ * return sum / d.f32(layout.$.boids.length);
36
+ * }
37
+ * ```
38
+ *
39
+ * Generates:
40
+ *
41
+ * ```wgsl
42
+ * @group(0) @binding(0) var<storage, read> boids: array<vec2f, 3>;
43
+ *
44
+ * fn centroid() -> vec2f {
45
+ * var sum = vec2f();
46
+ * // unrolled iteration #0
47
+ * sum += boids[0u];
48
+ * // unrolled iteration #1
49
+ * sum += boids[1u];
50
+ * // unrolled iteration #2
51
+ * sum += boids[2u];
52
+ * // ---
53
+ * return (sum / 3f);
54
+ * }
55
+ * ```
56
+ *
57
+ * @note
58
+ * Only the *value* of the argument is inspected, the expression itself is never emitted into
59
+ * the generated shader. Passing an expression with possible side effects (e.g. a call to a
60
+ * `tgpu.fn`) throws during shader generation, because those side effects would run in JS but
61
+ * silently not happen on the GPU.
62
+ *
63
+ * Such an expression is determined by shader execution, so it is never known at comptime and
64
+ * the check would always yield `false`. Remove the check, and if the side effect itself is
65
+ * needed, run it as a separate statement.
66
+ */
67
+ export declare const isKnownAtComptime: DualFn<(value: unknown) => boolean>;
@@ -0,0 +1,90 @@
1
+ import { bool } from "../data/numeric.js";
2
+ import { snip } from "../data/snippet.js";
3
+ import { WgslTypeError } from "../errors.js";
4
+ import { setName } from "../shared/meta.js";
5
+ import { $gpuCallable } from "../shared/symbols.js";
6
+ import { asComptime } from "../types.js";
7
+ /**
8
+ * Returns `true` if the value passed into it is statically known at comptime (during shader
9
+ * generation), and `false` if the value is determined by shader execution.
10
+ * During normal JavaScript execution every value is available right away, so it always
11
+ * returns `true`.
12
+ *
13
+ * Note that shader constants are NOT considered statically known at comptime, therefore
14
+ * `isKnownAtComptime()` returns `false` for them.
15
+ *
16
+ * A good example of where this is useful is opting into optimizations that are
17
+ * only valid when a value is statically known, like unrolling a loop whose iteration count
18
+ * depends on the size of an array:
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const layout = tgpu.bindGroupLayout({
23
+ * // Swapping this for `d.arrayOf(d.vec2f)` (a runtime-sized array)
24
+ * // makes the loop below stay a loop.
25
+ * boids: { storage: d.arrayOf(d.vec2f, 3) },
26
+ * });
27
+ *
28
+ * function centroid() {
29
+ * 'use gpu';
30
+ * let sum = d.vec2f();
31
+ *
32
+ * for (
33
+ * const boid of std.isKnownAtComptime(layout.$.boids.length)
34
+ * ? tgpu.unroll(layout.$.boids)
35
+ * : layout.$.boids
36
+ * ) {
37
+ * sum += boid;
38
+ * }
39
+ *
40
+ * return sum / d.f32(layout.$.boids.length);
41
+ * }
42
+ * ```
43
+ *
44
+ * Generates:
45
+ *
46
+ * ```wgsl
47
+ * @group(0) @binding(0) var<storage, read> boids: array<vec2f, 3>;
48
+ *
49
+ * fn centroid() -> vec2f {
50
+ * var sum = vec2f();
51
+ * // unrolled iteration #0
52
+ * sum += boids[0u];
53
+ * // unrolled iteration #1
54
+ * sum += boids[1u];
55
+ * // unrolled iteration #2
56
+ * sum += boids[2u];
57
+ * // ---
58
+ * return (sum / 3f);
59
+ * }
60
+ * ```
61
+ *
62
+ * @note
63
+ * Only the *value* of the argument is inspected, the expression itself is never emitted into
64
+ * the generated shader. Passing an expression with possible side effects (e.g. a call to a
65
+ * `tgpu.fn`) throws during shader generation, because those side effects would run in JS but
66
+ * silently not happen on the GPU.
67
+ *
68
+ * Such an expression is determined by shader execution, so it is never known at comptime and
69
+ * the check would always yield `false`. Remove the check, and if the side effect itself is
70
+ * needed, run it as a separate statement.
71
+ */
72
+ export const isKnownAtComptime = /* @__PURE__ */ (() => {
73
+ const impl = ((_value) => true);
74
+ impl.toString = () => 'isKnownAtComptime';
75
+ setName(impl, 'isKnownAtComptime');
76
+ impl[$gpuCallable] = {
77
+ call(_ctx, [value]) {
78
+ if (!value) {
79
+ throw new WgslTypeError('`std.isKnownAtComptime` was called without any arguments');
80
+ }
81
+ if (value.possibleSideEffects) {
82
+ throw new WgslTypeError('`std.isKnownAtComptime` received an argument with possible side effects. The expression is never emitted into the shader, so its side effects would silently not happen, and a side-effectful expression is never known at comptime anyway, so the result would always be `false`. Remove the check, and run the side effect as a separate statement if it is needed.');
83
+ }
84
+ return snip(asComptime(value) !== undefined, bool,
85
+ /* origin */ 'constant',
86
+ /* possibleSideEffects */ false);
87
+ },
88
+ };
89
+ return impl;
90
+ })();
package/std/index.d.ts CHANGED
@@ -18,3 +18,5 @@ export { extensionEnabled } from './extensions.ts';
18
18
  export { bitcastU32toF32, bitcastU32toI32, bitcastF32toU32, bitcast } from './bitcast.ts';
19
19
  export { range } from './range.ts';
20
20
  export { isBeingTranspiled, getTargetShaderLanguage, getShaderStage } from './environment.ts';
21
+ export { typeOf } from './typeOf.ts';
22
+ export { isKnownAtComptime } from './comptime.ts';
package/std/index.js CHANGED
@@ -30,3 +30,5 @@ export { extensionEnabled } from "./extensions.js";
30
30
  export { bitcastU32toF32, bitcastU32toI32, bitcastF32toU32, bitcast } from "./bitcast.js";
31
31
  export { range } from "./range.js";
32
32
  export { isBeingTranspiled, getTargetShaderLanguage, getShaderStage } from "./environment.js";
33
+ export { typeOf } from "./typeOf.js";
34
+ export { isKnownAtComptime } from "./comptime.js";
package/std/numeric.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type AnyFloat32VecInstance, type AnyFloatVecInstance, type AnyIntegerVecInstance, type AnyMatInstance, type AnyNumericVecInstance, type AnySignedVecInstance, type BaseData, type v2f, type v2h, type v2i, type v3f, type v3h, type v3i, type v4f, type v4h, type v4i, type Vec2f } from '../data/wgslTypes.ts';
2
2
  import type { Infer } from '../shared/repr.ts';
3
3
  type NumVec = AnyNumericVecInstance;
4
- export declare const unifyRestrictedSignature: (restrict: BaseData[]) => (...args: BaseData[]) => {
4
+ export declare function unifyRestrictedSignature(restrict: BaseData[]): (...args: BaseData[]) => {
5
5
  argTypes: BaseData[];
6
6
  returnType: BaseData;
7
7
  };
package/std/numeric.js CHANGED
@@ -26,16 +26,19 @@ const variadicUnifySignature = (...args) => {
26
26
  returnType: uargs[0],
27
27
  };
28
28
  };
29
- export const unifyRestrictedSignature = (restrict) => (...args) => {
30
- const uargs = unify(args, restrict);
31
- if (!uargs) {
32
- throw new SignatureNotSupportedError(args, restrict);
33
- }
34
- return {
35
- argTypes: uargs,
36
- returnType: uargs[0],
29
+ /*#__NO_SIDE_EFFECTS__*/
30
+ export function unifyRestrictedSignature(restrict) {
31
+ return (...args) => {
32
+ const uargs = unify(args, restrict);
33
+ if (!uargs) {
34
+ throw new SignatureNotSupportedError(args, restrict);
35
+ }
36
+ return {
37
+ argTypes: uargs,
38
+ returnType: uargs[0],
39
+ };
37
40
  };
38
- };
41
+ }
39
42
  function variadicReduce(fn) {
40
43
  return (fst, ...rest) => {
41
44
  let acc = fst;
@@ -747,10 +750,7 @@ export const round = dualImpl({
747
750
  });
748
751
  function cpuSaturate(value) {
749
752
  assertKind(value, floatKind);
750
- if (typeof value === 'number') {
751
- return Math.max(0, Math.min(1, value));
752
- }
753
- throw new MissingCpuImplError('CPU implementation for saturate on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues');
753
+ return generalizeFn((value) => clampScalar(value, 0, 1), [value]);
754
754
  }
755
755
  export const saturate = dualImpl({
756
756
  name: 'saturate',
package/std/packing.js CHANGED
@@ -96,7 +96,7 @@ export const unpack4x8unorm = dualImpl({
96
96
  return vec4f(reader.readUint8() / 255, reader.readUint8() / 255, reader.readUint8() / 255, reader.readUint8() / 255);
97
97
  },
98
98
  signature: { argTypes: [u32], returnType: vec4f },
99
- codegenImpl: (_ctx, [e]) => stitch `unpack4x8unorm(${e})`,
99
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('unpack4x8unorm', [], [e]),
100
100
  sideEffects: false,
101
101
  });
102
102
  /**
@@ -110,7 +110,7 @@ export const unpack4x8snorm = dualImpl({
110
110
  return vec4f(Math.max(reader.readInt8() / 127, -1), Math.max(reader.readInt8() / 127, -1), Math.max(reader.readInt8() / 127, -1), Math.max(reader.readInt8() / 127, -1));
111
111
  },
112
112
  signature: { argTypes: [u32], returnType: vec4f },
113
- codegenImpl: (_ctx, [e]) => stitch `unpack4x8snorm(${e})`,
113
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('unpack4x8snorm', [], [e]),
114
114
  sideEffects: false,
115
115
  });
116
116
  /**
@@ -124,7 +124,7 @@ export const unpack4xI8 = dualImpl({
124
124
  return vec4i(reader.readInt8(), reader.readInt8(), reader.readInt8(), reader.readInt8());
125
125
  },
126
126
  signature: { argTypes: [u32], returnType: vec4i },
127
- codegenImpl: (_ctx, [e]) => stitch `unpack4xI8(${e})`,
127
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('unpack4xI8', [], [e]),
128
128
  sideEffects: false,
129
129
  });
130
130
  /**
@@ -138,7 +138,7 @@ export const unpack4xU8 = dualImpl({
138
138
  return vec4u(reader.readUint8(), reader.readUint8(), reader.readUint8(), reader.readUint8());
139
139
  },
140
140
  signature: { argTypes: [u32], returnType: vec4u },
141
- codegenImpl: (_ctx, [e]) => stitch `unpack4xU8(${e})`,
141
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('unpack4xU8', [], [e]),
142
142
  sideEffects: false,
143
143
  });
144
144
  /**
@@ -182,7 +182,7 @@ export const pack4x8unorm = dualImpl({
182
182
  writer.writeUint8(Math.floor(0.5 + 255 * clampScalar(e.w, 0, 1)));
183
183
  }),
184
184
  signature: { argTypes: [vec4f], returnType: u32 },
185
- codegenImpl: (_ctx, [e]) => stitch `pack4x8unorm(${e})`,
185
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('pack4x8unorm', [], [e]),
186
186
  sideEffects: false,
187
187
  });
188
188
  /**
@@ -198,7 +198,7 @@ export const pack4x8snorm = dualImpl({
198
198
  writer.writeInt8(Math.floor(0.5 + 127 * clampScalar(e.w, -1, 1)));
199
199
  }),
200
200
  signature: { argTypes: [vec4f], returnType: u32 },
201
- codegenImpl: (_ctx, [e]) => stitch `pack4x8snorm(${e})`,
201
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('pack4x8snorm', [], [e]),
202
202
  sideEffects: false,
203
203
  });
204
204
  /**
@@ -214,7 +214,7 @@ export const pack4xI8 = dualImpl({
214
214
  writer.writeInt8(e.w);
215
215
  }),
216
216
  signature: { argTypes: [vec4i], returnType: u32 },
217
- codegenImpl: (_ctx, [e]) => stitch `pack4xI8(${e})`,
217
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('pack4xI8', [], [e]),
218
218
  sideEffects: false,
219
219
  });
220
220
  /**
@@ -230,7 +230,7 @@ export const pack4xU8 = dualImpl({
230
230
  writer.writeUint8(e.w);
231
231
  }),
232
232
  signature: { argTypes: [vec4u], returnType: u32 },
233
- codegenImpl: (_ctx, [e]) => stitch `pack4xU8(${e})`,
233
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('pack4xU8', [], [e]),
234
234
  sideEffects: false,
235
235
  });
236
236
  /**
@@ -246,7 +246,7 @@ export const pack4xI8Clamp = dualImpl({
246
246
  writer.writeInt8(clampScalar(e.w, -128, 127));
247
247
  }),
248
248
  signature: { argTypes: [vec4i], returnType: u32 },
249
- codegenImpl: (_ctx, [e]) => stitch `pack4xI8Clamp(${e})`,
249
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('pack4xI8Clamp', [], [e]),
250
250
  sideEffects: false,
251
251
  });
252
252
  /**
@@ -262,6 +262,6 @@ export const pack4xU8Clamp = dualImpl({
262
262
  writer.writeUint8(clampScalar(e.w, 0, 255));
263
263
  }),
264
264
  signature: { argTypes: [vec4u], returnType: u32 },
265
- codegenImpl: (_ctx, [e]) => stitch `pack4xU8Clamp(${e})`,
265
+ codegenImpl: (ctx, [e]) => ctx.gen.emitCall('pack4xU8Clamp', [], [e]),
266
266
  sideEffects: false,
267
267
  });