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
@@ -33,14 +33,15 @@ export type AspectInfo = {
33
33
  export type TextureFormatInfo = {
34
34
  readonly channelType: F32 | I32 | U32;
35
35
  readonly vectorType: Vec4f | Vec4i | Vec4u;
36
- readonly texelSize: number | 'non-copyable';
36
+ readonly texelBlockSize: number | 'non-copyable';
37
+ readonly blockDimensions: readonly [number, number];
37
38
  readonly sampleTypes: readonly GPUTextureSampleType[];
38
39
  readonly canRenderAttachment: boolean;
39
40
  readonly depthAspect?: AspectInfo & {
40
- readonly texelSize: number | 'non-copyable';
41
+ readonly texelBlockSize: number | 'non-copyable';
41
42
  };
42
43
  readonly stencilAspect?: AspectInfo & {
43
- readonly texelSize: number;
44
+ readonly texelBlockSize: number;
44
45
  };
45
46
  };
46
47
  export declare function getTextureFormatInfo(format: GPUTextureFormat): TextureFormatInfo;
@@ -4,25 +4,25 @@ const DEPTH_ASPECT_NON_COPYABLE = {
4
4
  channelType: f32,
5
5
  vectorType: vec4f,
6
6
  sampleTypes: ['depth', 'unfilterable-float'],
7
- texelSize: 'non-copyable',
7
+ texelBlockSize: 'non-copyable',
8
8
  };
9
9
  const DEPTH_ASPECT_16 = {
10
10
  channelType: f32,
11
11
  vectorType: vec4f,
12
12
  sampleTypes: ['depth', 'unfilterable-float'],
13
- texelSize: 2,
13
+ texelBlockSize: 2,
14
14
  };
15
15
  const DEPTH_ASPECT_32 = {
16
16
  channelType: f32,
17
17
  vectorType: vec4f,
18
18
  sampleTypes: ['depth', 'unfilterable-float'],
19
- texelSize: 4,
19
+ texelBlockSize: 4,
20
20
  };
21
21
  const STENCIL_ASPECT = {
22
22
  channelType: u32,
23
23
  vectorType: vec4u,
24
24
  sampleTypes: ['uint'],
25
- texelSize: 1,
25
+ texelBlockSize: 1,
26
26
  };
27
27
  const formatInfoCache = new Map();
28
28
  export function getTextureFormatInfo(format) {
@@ -40,7 +40,8 @@ function createFormatInfo(format) {
40
40
  return {
41
41
  channelType,
42
42
  vectorType: channelType === u32 ? vec4u : channelType === i32 ? vec4i : vec4f,
43
- texelSize: parseTexelSize(format),
43
+ texelBlockSize: parseTexelBlockSize(format),
44
+ blockDimensions: parseBlockDimensions(format),
44
45
  sampleTypes: parseSampleTypes(format),
45
46
  canRenderAttachment: canRenderAttachment(format),
46
47
  ...(depthAspect && { depthAspect }),
@@ -78,7 +79,7 @@ function parseChannelType(format) {
78
79
  return i32;
79
80
  return f32;
80
81
  }
81
- function parseTexelSize(format) {
82
+ function parseTexelBlockSize(format) {
82
83
  // Standard formats: channel count encoded in prefix length (r=1, rg=2, rgba/bgra=4)
83
84
  const [, channels, bits] = format.match(/^(rgba|bgra|rg|r)(8|16|32)/) ?? [];
84
85
  if (channels && bits) {
@@ -106,6 +107,16 @@ function parseTexelSize(format) {
106
107
  // Packed 32-bit (rgb9e5ufloat, rgb10a2unorm, rgb10a2uint, rg11b10ufloat)
107
108
  return 4;
108
109
  }
110
+ function parseBlockDimensions(format) {
111
+ const astc = /^astc-(\d+)x(\d+)-/.exec(format);
112
+ if (astc) {
113
+ return [Number(astc[1]), Number(astc[2])];
114
+ }
115
+ if (format.startsWith('bc') || format.startsWith('etc2-') || format.startsWith('eac-')) {
116
+ return [4, 4];
117
+ }
118
+ return [1, 1];
119
+ }
109
120
  function parseSampleTypes(format) {
110
121
  if (format === 'stencil8')
111
122
  return ['uint'];
@@ -1,3 +1,4 @@
1
+ import type { TextureFormatInfo } from './textureFormats.ts';
1
2
  import type { TextureProps } from './textureProps.ts';
2
3
  export type TextureWriteFit = 'stretch' | 'clip';
3
4
  export type TextureWriteOptions = {
@@ -54,6 +55,14 @@ export declare function origin3d([x, y, z]?: readonly (number | undefined)[]): {
54
55
  z: number;
55
56
  };
56
57
  export declare function mipLevelSize({ size, dimension }: TextureShape, mipLevel: number): [number, number, number];
58
+ export declare function getTextureCopyLayout([width, height, depth]: readonly [number, number, number], { blockDimensions: [blockWidth, blockHeight], texelBlockSize, }: Pick<TextureFormatInfo, 'blockDimensions' | 'texelBlockSize'>): {
59
+ extent: [number, number, number];
60
+ dataLayout: {
61
+ bytesPerRow: number;
62
+ rowsPerImage: number;
63
+ byteSize: number;
64
+ } | undefined;
65
+ };
57
66
  /** The size of the written region: `size`, or the rest of the mip level past `origin` */
58
67
  export declare function writeRegionSize(texture: TextureShape, options: TextureWriteOptions): [number, number];
59
68
  export declare function sameSize(a: readonly number[], b: readonly number[]): boolean;
@@ -5,6 +5,27 @@ export function mipLevelSize({ size, dimension }, mipLevel) {
5
5
  const scale = (value = 1) => Math.max(1, value >> mipLevel);
6
6
  return [scale(size[0]), scale(size[1]), dimension === '3d' ? scale(size[2]) : (size[2] ?? 1)];
7
7
  }
8
+ export function getTextureCopyLayout([width, height, depth], { blockDimensions: [blockWidth, blockHeight], texelBlockSize, }) {
9
+ const blocksAcross = Math.ceil(width / blockWidth);
10
+ const blockRows = Math.ceil(height / blockHeight);
11
+ const extent = [
12
+ blocksAcross * blockWidth,
13
+ blockRows * blockHeight,
14
+ depth,
15
+ ];
16
+ if (texelBlockSize === 'non-copyable') {
17
+ return { extent, dataLayout: undefined };
18
+ }
19
+ const bytesPerRow = blocksAcross * texelBlockSize;
20
+ return {
21
+ extent,
22
+ dataLayout: {
23
+ bytesPerRow,
24
+ rowsPerImage: blockRows,
25
+ byteSize: bytesPerRow * blockRows * depth,
26
+ },
27
+ };
28
+ }
8
29
  /** The size of the written region: `size`, or the rest of the mip level past `origin` */
9
30
  export function writeRegionSize(texture, options) {
10
31
  const [mipWidth, mipHeight] = mipLevelSize(texture, options.mipLevel ?? 0);
@@ -84,10 +84,8 @@ export const unroll = (() => {
84
84
  setName(impl, 'unroll');
85
85
  impl.toString = () => 'unroll';
86
86
  impl[$internal] = true;
87
- impl[$gpuCallable] = {
88
- call(_ctx, [value]) {
89
- return withValue(new UnrollableIterable(value), value);
90
- },
87
+ impl[$gpuCallable] = (_ctx, [value]) => {
88
+ return withValue(new UnrollableIterable(value), value);
91
89
  };
92
90
  return impl;
93
91
  })();
@@ -1,5 +1,5 @@
1
1
  import type { Disarray, LooseDecorated, Unstruct } from '../../data/dataTypes.ts';
2
- import type { FormatToAcceptedData, FormatToWGSLType } from '../../data/vertexFormatData.ts';
2
+ import type { FormatToWGSLType } from '../../data/vertexFormatData.ts';
3
3
  import type { Decorated, WgslArray, WgslStruct } from '../../data/wgslTypes.ts';
4
4
  import type { KindToAcceptedAttribMap, KindToDefaultFormatMap, TgpuVertexAttrib, VertexFormat } from '../../shared/vertexFormat.ts';
5
5
  /**
@@ -29,6 +29,3 @@ export type LayoutToAllowedAttribs<T> = T extends {
29
29
  export type AttribRecordToDefaultDataTypes<T extends Record<string, TgpuVertexAttrib>> = {
30
30
  [Key in keyof T]: FormatToWGSLType<T[Key]['format']>;
31
31
  };
32
- export type AttribRecordToAcceptedDataTypes<T extends Record<string, TgpuVertexAttrib>> = {
33
- [Key in keyof T]: FormatToAcceptedData[T[Key]['format']];
34
- };
@@ -1,8 +1,7 @@
1
- import { alignmentOf, customAlignmentOf } from "../../data/alignmentOf.js";
2
1
  import { getCustomLocation, isLooseDecorated, isUnstruct } from "../../data/dataTypes.js";
3
- import { sizeOf } from "../../data/sizeOf.js";
2
+ import { offsetsForProps } from "../../data/offsets.js";
3
+ import { strideOf } from "../../data/schemaMemoryLayout.js";
4
4
  import { isDecorated, isWgslStruct } from "../../data/wgslTypes.js";
5
- import { roundUp } from "../../mathUtils.js";
6
5
  import { setName } from "../../shared/meta.js";
7
6
  import { $internal, $soul } from "../../shared/symbols.js";
8
7
  import { kindToDefaultFormatMap, vertexFormats, } from "../../shared/vertexFormat.js";
@@ -22,33 +21,15 @@ function dataToContainedAttribs(layout, data, offset, customLocationMap, key) {
22
21
  if (customLocation !== undefined) {
23
22
  customLocationMap[key ?? defaultAttribEntry] = customLocation;
24
23
  }
25
- return dataToContainedAttribs(layout, data.inner, roundUp(offset, customAlignmentOf(data)), customLocationMap);
24
+ // passing offset unchanged because the parent already applied alignment
25
+ return dataToContainedAttribs(layout, data.inner, offset, customLocationMap);
26
26
  }
27
- if (isWgslStruct(data)) {
28
- let memberOffset = offset;
29
- const propTypes = data.propTypes;
30
- return Object.fromEntries(Object.entries(propTypes).map(([key, value]) => {
31
- memberOffset = roundUp(memberOffset, alignmentOf(value));
32
- const attrib = [
33
- key,
34
- dataToContainedAttribs(layout, value, memberOffset, customLocationMap, key),
35
- ];
36
- memberOffset += sizeOf(value);
37
- return attrib;
38
- }));
39
- }
40
- if (isUnstruct(data)) {
41
- let memberOffset = offset;
42
- const propTypes = data.propTypes;
43
- return Object.fromEntries(Object.entries(propTypes).map(([key, value]) => {
44
- memberOffset = roundUp(memberOffset, customAlignmentOf(value));
45
- const attrib = [
46
- key,
47
- dataToContainedAttribs(layout, value, memberOffset, customLocationMap, key),
48
- ];
49
- memberOffset += sizeOf(value);
50
- return attrib;
51
- }));
27
+ if (isWgslStruct(data) || isUnstruct(data)) {
28
+ const offsets = offsetsForProps(data);
29
+ return Object.fromEntries(Object.entries(data.propTypes).map(([key, value]) => [
30
+ key,
31
+ dataToContainedAttribs(layout, value, offset + offsets[key].offset, customLocationMap, key),
32
+ ]));
52
33
  }
53
34
  if ('type' in data && typeof data.type === 'string') {
54
35
  if (vertexFormats.includes(data.type)) {
@@ -89,7 +70,7 @@ class TgpuVertexLayoutImpl {
89
70
  stepMode,
90
71
  label: undefined,
91
72
  };
92
- this.stride = roundUp(sizeOf(arraySchema.elementType), alignmentOf(arraySchema));
73
+ this.stride = strideOf(arraySchema);
93
74
  this.attrib = dataToContainedAttribs(this, arraySchema.elementType, 0, this.#customLocationMap);
94
75
  }
95
76
  get stepMode() {
@@ -5,4 +5,4 @@ export declare function customAlignmentOf(data: BaseData): number;
5
5
  /**
6
6
  * Returns the alignment (in bytes) of data represented by the `schema`.
7
7
  */
8
- export declare function PUBLIC_alignmentOf(schema: AnyData): number;
8
+ export declare const PUBLIC_alignmentOf: import("../indexNamedExports.ts").TgpuComptime<(schema: AnyData) => number>;
@@ -1,3 +1,4 @@
1
+ import { comptime } from "../core/function/comptime.js";
1
2
  import { safeStringify } from "../shared/stringify.js";
2
3
  import { getCustomAlignment, isDisarray, isLooseDecorated, isUnstruct, } from "./dataTypes.js";
3
4
  import { packedFormats } from "./vertexFormatData.js";
@@ -43,13 +44,8 @@ function computeAlignment(data) {
43
44
  if (isWgslArray(data)) {
44
45
  return alignmentOf(data.elementType);
45
46
  }
46
- if (isUnstruct(data)) {
47
- // A loose struct is aligned to its first property.
48
- const firstProp = Object.values(data.propTypes)[0];
49
- return firstProp ? (getCustomAlignment(firstProp) ?? 1) : 1;
50
- }
51
- if (isDisarray(data)) {
52
- return getCustomAlignment(data.elementType) ?? 1;
47
+ if (isUnstruct(data) || isDisarray(data)) {
48
+ return customAlignmentOf(data);
53
49
  }
54
50
  if (isDecorated(data) || isLooseDecorated(data)) {
55
51
  return getCustomAlignment(data) ?? alignmentOf(data.inner);
@@ -60,8 +56,7 @@ function computeAlignment(data) {
60
56
  throw new Error(`Cannot determine alignment of data: ${safeStringify(data)}`);
61
57
  }
62
58
  function computeCustomAlignment(data) {
63
- if (isUnstruct(data)) {
64
- // A loose struct is aligned to its first property.
59
+ if (isUnstruct(data) || isWgslStruct(data)) {
65
60
  const firstProp = Object.values(data.propTypes)[0];
66
61
  return firstProp ? customAlignmentOf(firstProp) : 1;
67
62
  }
@@ -98,6 +93,4 @@ export function customAlignmentOf(data) {
98
93
  /**
99
94
  * Returns the alignment (in bytes) of data represented by the `schema`.
100
95
  */
101
- export function PUBLIC_alignmentOf(schema) {
102
- return alignmentOf(schema);
103
- }
96
+ export const PUBLIC_alignmentOf = comptime((schema) => alignmentOf(schema));
package/data/array.js CHANGED
@@ -1,7 +1,11 @@
1
1
  import { comptime } from "../core/function/comptime.js";
2
- import { $internal } from "../shared/symbols.js";
2
+ import { WgslTypeError } from "../errors.js";
3
+ import { $gpuCallable, $gpuCallableStrictSignature, $internal } from "../shared/symbols.js";
4
+ import { tryConvertSnippet } from "../tgsl/conversion.js";
5
+ import { ArrayExpression } from "../tgsl/generationHelpers.js";
3
6
  import { schemaCallWrapper } from "./schemaCallWrapper.js";
4
7
  import { sizeOf } from "./sizeOf.js";
8
+ import { fallthroughCopyOrigin, snip } from "./snippet.js";
5
9
  import { isDecorated, isLocationAttrib } from "./wgslTypes.js";
6
10
  /**
7
11
  * Creates an array schema that can be used to construct gpu buffers.
@@ -57,9 +61,37 @@ function cpu_arrayOf(elementType, elementCount) {
57
61
  return arraySchema;
58
62
  }
59
63
  const WgslArrayImpl = {
60
- [$internal]: true,
64
+ [$internal]: {},
61
65
  type: 'array',
62
66
  toString() {
63
67
  return `arrayOf(${String(this.elementType)}, ${this.elementCount})`;
64
68
  },
69
+ get [$gpuCallableStrictSignature]() {
70
+ return { argTypes: [this], returnType: this };
71
+ },
72
+ [$gpuCallable](ctx, args) {
73
+ // Array schema call.
74
+ if (args.length > 1) {
75
+ throw new WgslTypeError('Array schemas should always be called with at most 1 argument');
76
+ }
77
+ // No arguments `array<...>()`, resolve array type and return.
78
+ if (!args[0]) {
79
+ // The schema becomes the data type.
80
+ return ctx.gen.typeInstantiation(this, []);
81
+ }
82
+ const arg = tryConvertSnippet(ctx, args[0], this);
83
+ // `d.arrayOf(...)([...])`.
84
+ // We don't resolve the ArrayExpression object itself to
85
+ // avoid reference checks (we're copying so it's fine)
86
+ if (arg.value instanceof ArrayExpression) {
87
+ return ctx.gen.typeInstantiation(this, arg.value.elements);
88
+ }
89
+ // `d.arrayOf(...)(otherArr)`.
90
+ // We just let the argument resolve everything.
91
+ return snip(ctx.resolveSnippet(arg).value, this,
92
+ // A new array, so not a reference.
93
+ /* origin */ fallthroughCopyOrigin(arg.origin), arg.possibleSideEffects);
94
+ },
65
95
  };
96
+ // Schemas are still functions, so they should keep `call`, `apply`, `bind`, etc.
97
+ Object.setPrototypeOf(WgslArrayImpl, Function.prototype);
@@ -6,21 +6,33 @@ export type AnyAttribute<AllowedBuiltins extends Builtin<BuiltinName> = Builtin<
6
6
  export type ExtractAttributes<T> = T extends {
7
7
  readonly attribs: unknown[];
8
8
  } ? T['attribs'] : [];
9
+ /**
10
+ * `TAttribs` without the attributes of type `TType`. An array that is not a tuple is kept as it is.
11
+ */
12
+ type WithoutAttribute<TAttribs extends unknown[], TType> = number extends TAttribs['length'] ? TAttribs : TAttribs extends [infer Head, ...infer Rest] ? Head extends {
13
+ readonly type: TType;
14
+ } ? WithoutAttribute<Rest, TType> : [Head, ...WithoutAttribute<Rest, TType>] : [];
9
15
  /**
10
16
  * Decorates a data-type `TData` with an attribute `TAttrib`.
11
17
  *
12
18
  * - if `TData` is loose
13
19
  * - if `TData` is already `LooseDecorated`
14
- * - Prepend `TAttrib` to the existing attribute tuple.
20
+ * - Prepend `TAttrib` to the existing attribute tuple, replacing an attribute of the same type.
15
21
  * - else
16
22
  * - Wrap `TData` with `LooseDecorated` and a single attribute `[TAttrib]`
17
23
  * - else
18
24
  * - if `TData` is already `Decorated`
19
- * - Prepend `TAttrib` to the existing attribute tuple.
25
+ * - Prepend `TAttrib` to the existing attribute tuple, replacing an attribute of the same type.
20
26
  * - else
21
27
  * - Wrap `TData` with `Decorated` and a single attribute `[TAttrib]`
22
28
  */
23
- export type Decorate<TData extends BaseData, TAttrib extends AnyAttribute> = IsWgslData<TData> extends true ? Decorated<Undecorate<TData>, [TAttrib, ...ExtractAttributes<TData>]> : IsLooseData<TData> extends true ? LooseDecorated<Undecorate<TData>, [TAttrib, ...ExtractAttributes<TData>]> : never;
29
+ export type Decorate<TData extends BaseData, TAttrib extends AnyAttribute> = IsWgslData<TData> extends true ? Decorated<Undecorate<TData>, [
30
+ TAttrib,
31
+ ...WithoutAttribute<ExtractAttributes<TData>, TAttrib['type']>
32
+ ]> : IsLooseData<TData> extends true ? LooseDecorated<Undecorate<TData>, [
33
+ TAttrib,
34
+ ...WithoutAttribute<ExtractAttributes<TData>, TAttrib['type']>
35
+ ]> : never;
24
36
  export type IsBuiltin<T> = ExtractAttributes<T>[number] extends [] ? false : ExtractAttributes<T>[number] extends Builtin<BuiltinName> ? true : false;
25
37
  export type HasCustomLocation<T> = ExtractAttributes<T>[number] extends [] ? false : ExtractAttributes<T>[number] extends Location ? true : false;
26
38
  export declare function attribute(data: BaseData, attrib: AnyAttribute): Decorated | LooseDecorated;
@@ -117,3 +129,4 @@ export declare function interpolate<TInterpolation extends FlatInterpolationType
117
129
  export declare function invariant(data: Decorated<Vec4f, [Builtin<'position'>]>): Decorated<Vec4f, [Builtin<'position'>, Invariant]>;
118
130
  export declare function isBuiltin(value: unknown): value is Decorated<AnyWgslData, AnyAttribute[]> | LooseDecorated<AnyLooseData, AnyAttribute[]>;
119
131
  export declare function getAttributesString<T extends BaseData>(field: T): string;
132
+ export {};
@@ -30,12 +30,21 @@ export const builtinNames = [
30
30
  'subgroup_id',
31
31
  'num_subgroups',
32
32
  ];
33
+ /**
34
+ * WGSL allows one attribute of each kind, so a new decorator replaces an existing one of the same kind.
35
+ */
36
+ function withAttribute(attribs, attrib) {
37
+ return [
38
+ attrib,
39
+ ...attribs.filter((existing) => existing.type !== attrib.type),
40
+ ];
41
+ }
33
42
  export function attribute(data, attrib) {
34
43
  if (isDecorated(data)) {
35
- return new DecoratedImpl(data.inner, [attrib, ...data.attribs]);
44
+ return new DecoratedImpl(data.inner, withAttribute(data.attribs, attrib));
36
45
  }
37
46
  if (isLooseDecorated(data)) {
38
- return new LooseDecoratedImpl(data.inner, [attrib, ...data.attribs]);
47
+ return new LooseDecoratedImpl(data.inner, withAttribute(data.attribs, attrib));
39
48
  }
40
49
  if (isLooseData(data)) {
41
50
  return new LooseDecoratedImpl(data, [attrib]);
@@ -1,9 +1,9 @@
1
1
  import { roundUp } from "../mathUtils.js";
2
2
  import { logger } from "../tgpuLogger.js";
3
- import { alignmentOf } from "./alignmentOf.js";
4
3
  import { isDisarray, isLooseDecorated, isUnstruct } from "./dataTypes.js";
5
4
  import { offsetsForProps } from "./offsets.js";
6
5
  import { sizeOf } from "./sizeOf.js";
6
+ import { strideOf } from "./schemaMemoryLayout.js";
7
7
  import { formatToWGSLType, isPackedData } from "./vertexFormatData.js";
8
8
  import * as wgsl from "./wgslTypes.js";
9
9
  export const EVAL_ALLOWED_IN_ENV = (() => {
@@ -112,7 +112,7 @@ const vertexFormatValueTransform = {
112
112
  const specialPackedFormats = {
113
113
  'unorm10-10-10-2': {
114
114
  writeFunction: 'setUint32',
115
- generator: (offsetExpr, valueExpr) => `output.setUint32(${offsetExpr}, ((${valueExpr}.x*1023&0x3FF)<<22)|((${valueExpr}.y*1023&0x3FF)<<12)|((${valueExpr}.z*1023&0x3FF)<<2)|(${valueExpr}.w*3&3), littleEndian);\n`,
115
+ generator: (offsetExpr, valueExpr) => `output.setUint32(${offsetExpr}, ((Math.round(${valueExpr}.x*1023)&0x3FF)<<22)|((Math.round(${valueExpr}.y*1023)&0x3FF)<<12)|((Math.round(${valueExpr}.z*1023)&0x3FF)<<2)|(Math.round(${valueExpr}.w*3)&3), littleEndian);\n`,
116
116
  },
117
117
  'unorm8x4-bgra': {
118
118
  writeFunction: 'setUint8',
@@ -148,7 +148,7 @@ export function buildWriter(node, offsetExpr, valueExpr, depth = 0, partial = fa
148
148
  if (node.elementCount === 0) {
149
149
  throw new Error('Cannot write using a runtime-sized schema.');
150
150
  }
151
- const elementSize = roundUp(sizeOf(node.elementType), alignmentOf(node));
151
+ const elementSize = strideOf(node);
152
152
  const totalSize = node.elementCount * elementSize;
153
153
  const copyLen = partial
154
154
  ? `Math.min(${valueExpr}.byteLength, Math.max(0, endOffset - (${offsetExpr})))`