@luma.gl/graph 10.0.0-alpha.12 → 10.0.0-alpha.14

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 (145) hide show
  1. package/LICENSE +4 -4
  2. package/THIRD-PARTY-NOTICES.md +19 -0
  3. package/dist/arrow/arrow-colors.cjs +99 -18
  4. package/dist/arrow/arrow-colors.d.ts +27 -10
  5. package/dist/arrow/arrow-colors.d.ts.map +1 -1
  6. package/dist/arrow/arrow-colors.js +107 -24
  7. package/dist/arrow/arrow-colors.js.map +1 -1
  8. package/dist/arrow/gpu/arrow-gpu-vector-adapters.cjs +8 -6
  9. package/dist/arrow/gpu/arrow-gpu-vector-adapters.d.ts +1 -0
  10. package/dist/arrow/gpu/arrow-gpu-vector-adapters.d.ts.map +1 -1
  11. package/dist/arrow/gpu/arrow-gpu-vector-adapters.js +17 -7
  12. package/dist/arrow/gpu/arrow-gpu-vector-adapters.js.map +1 -1
  13. package/dist/arrow/gpu/arrow-gpu-vector-conversion.cjs +35 -5
  14. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts +6 -1
  15. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts.map +1 -1
  16. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js +40 -5
  17. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js.map +1 -1
  18. package/dist/arrow/index.cjs.map +3 -3
  19. package/dist/arrow/internal.cjs.map +2 -2
  20. package/dist/dist.dev.js +1506 -163
  21. package/dist/dist.min.js +401 -105
  22. package/dist/gpu-core/gpu-expression-operation.cjs +1 -1
  23. package/dist/gpu-core/gpu-expression-operation.d.ts +1 -1
  24. package/dist/gpu-core/gpu-expression-operation.d.ts.map +1 -1
  25. package/dist/gpu-core/gpu-expression-operation.js +1 -1
  26. package/dist/gpu-core/gpu-expression-operation.js.map +1 -1
  27. package/dist/gpu-core/gpu-graph-compiler.cjs +48 -0
  28. package/dist/gpu-core/gpu-graph-compiler.d.ts +1 -0
  29. package/dist/gpu-core/gpu-graph-compiler.d.ts.map +1 -1
  30. package/dist/gpu-core/gpu-graph-compiler.js +50 -0
  31. package/dist/gpu-core/gpu-graph-compiler.js.map +1 -1
  32. package/dist/gpu-core/gpu-group-aggregation.cjs +7 -15
  33. package/dist/gpu-core/gpu-group-aggregation.d.ts.map +1 -1
  34. package/dist/gpu-core/gpu-group-aggregation.js +7 -18
  35. package/dist/gpu-core/gpu-group-aggregation.js.map +1 -1
  36. package/dist/gpu-core/gpu-reduction.cjs +6 -14
  37. package/dist/gpu-core/gpu-reduction.d.ts.map +1 -1
  38. package/dist/gpu-core/gpu-reduction.js +6 -15
  39. package/dist/gpu-core/gpu-reduction.js.map +1 -1
  40. package/dist/gpu-core/gpu-semantic-aggregation-operation.cjs +112 -0
  41. package/dist/gpu-core/gpu-semantic-aggregation-operation.d.ts +71 -0
  42. package/dist/gpu-core/gpu-semantic-aggregation-operation.d.ts.map +1 -0
  43. package/dist/gpu-core/gpu-semantic-aggregation-operation.js +92 -0
  44. package/dist/gpu-core/gpu-semantic-aggregation-operation.js.map +1 -0
  45. package/dist/gpu-core/index.cjs +5 -0
  46. package/dist/gpu-core/index.cjs.map +3 -3
  47. package/dist/gpu-core/index.d.ts +2 -0
  48. package/dist/gpu-core/index.d.ts.map +1 -1
  49. package/dist/gpu-core/index.js +1 -0
  50. package/dist/gpu-core/index.js.map +1 -1
  51. package/dist/gpu-data/color-conversion.cjs +105 -0
  52. package/dist/gpu-data/color-conversion.d.ts +30 -0
  53. package/dist/gpu-data/color-conversion.d.ts.map +1 -0
  54. package/dist/gpu-data/color-conversion.js +109 -0
  55. package/dist/gpu-data/color-conversion.js.map +1 -0
  56. package/dist/gpu-data/cpu-gpu-vector-transfer.cjs +7 -2
  57. package/dist/gpu-data/cpu-gpu-vector-transfer.d.ts.map +1 -1
  58. package/dist/gpu-data/cpu-gpu-vector-transfer.js +9 -6
  59. package/dist/gpu-data/cpu-gpu-vector-transfer.js.map +1 -1
  60. package/dist/gpu-data/gpu-data-buffer-props.cjs +41 -0
  61. package/dist/gpu-data/gpu-data-buffer-props.d.ts +5 -0
  62. package/dist/gpu-data/gpu-data-buffer-props.d.ts.map +1 -0
  63. package/dist/gpu-data/gpu-data-buffer-props.js +19 -0
  64. package/dist/gpu-data/gpu-data-buffer-props.js.map +1 -0
  65. package/dist/gpu-data/index.cjs +7 -2
  66. package/dist/gpu-data/index.cjs.map +3 -3
  67. package/dist/gpu-data/index.d.ts +2 -0
  68. package/dist/gpu-data/index.d.ts.map +1 -1
  69. package/dist/gpu-data/index.js +1 -0
  70. package/dist/gpu-data/index.js.map +1 -1
  71. package/dist/gpu-graph/index.cjs +5 -0
  72. package/dist/gpu-graph/index.cjs.map +3 -3
  73. package/dist/gpu-graph/index.d.ts +2 -0
  74. package/dist/gpu-graph/index.d.ts.map +1 -1
  75. package/dist/gpu-graph/index.js +1 -0
  76. package/dist/gpu-graph/index.js.map +1 -1
  77. package/dist/gpu-graph-algorithms/benchmarks.cjs.map +1 -1
  78. package/dist/gpu-graph-algorithms/index.cjs.map +1 -1
  79. package/dist/gpu-project/benchmarks.cjs.map +2 -2
  80. package/dist/gpu-project/crs.cjs.map +2 -2
  81. package/dist/gpu-project/graph.cjs.map +3 -3
  82. package/dist/gpu-project/index.cjs.map +2 -2
  83. package/dist/gpu-simple-graph/index.cjs.map +3 -3
  84. package/dist/gpu-simple-graph/index.d.ts +1 -1
  85. package/dist/gpu-simple-graph/index.d.ts.map +1 -1
  86. package/dist/gpu-simple-graph/index.js.map +1 -1
  87. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.cjs +2 -0
  88. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.js +3 -0
  89. package/dist/gpu-simple-graph/operation/gpu-data-evaluator.js.map +1 -1
  90. package/dist/gpu-simple-graph/operations/convert-colors.cjs +6 -6
  91. package/dist/gpu-simple-graph/operations/convert-colors.d.ts +5 -1
  92. package/dist/gpu-simple-graph/operations/convert-colors.d.ts.map +1 -1
  93. package/dist/gpu-simple-graph/operations/convert-colors.js +12 -7
  94. package/dist/gpu-simple-graph/operations/convert-colors.js.map +1 -1
  95. package/dist/gpu-simple-graph/operations/cpu/convert-colors.cjs +16 -33
  96. package/dist/gpu-simple-graph/operations/cpu/convert-colors.d.ts.map +1 -1
  97. package/dist/gpu-simple-graph/operations/cpu/convert-colors.js +22 -35
  98. package/dist/gpu-simple-graph/operations/cpu/convert-colors.js.map +1 -1
  99. package/dist/gpu-simple-graph/operations/cpu/index.cjs.map +3 -3
  100. package/dist/gpu-simple-graph/operations/webgl/index.cjs.map +3 -3
  101. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.cjs +31 -13
  102. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.d.ts.map +1 -1
  103. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.js +42 -13
  104. package/dist/gpu-simple-graph/operations/webgpu/convert-colors.js.map +1 -1
  105. package/dist/gpu-simple-graph/operations/webgpu/index.cjs.map +1 -1
  106. package/dist/gpu-sql/gpu-sql.cjs +112 -100
  107. package/dist/gpu-sql/gpu-sql.d.ts +1 -1
  108. package/dist/gpu-sql/gpu-sql.d.ts.map +1 -1
  109. package/dist/gpu-sql/gpu-sql.js +120 -102
  110. package/dist/gpu-sql/gpu-sql.js.map +1 -1
  111. package/dist/gpu-sql/index.cjs.map +2 -2
  112. package/dist/gpu-tables/index.cjs.map +2 -2
  113. package/dist/gpu-tables/table/gpu-table.cjs +2 -2
  114. package/dist/gpu-tables/table/gpu-table.d.ts.map +1 -1
  115. package/dist/gpu-tables/table/gpu-table.js +2 -2
  116. package/dist/gpu-tables/table/gpu-table.js.map +1 -1
  117. package/dist/index.cjs +5 -0
  118. package/dist/index.cjs.map +3 -3
  119. package/dist/index.d.ts +2 -0
  120. package/dist/index.d.ts.map +1 -1
  121. package/dist/index.js +1 -0
  122. package/dist/index.js.map +1 -1
  123. package/package.json +11 -8
  124. package/src/arrow/arrow-colors.ts +194 -33
  125. package/src/arrow/gpu/arrow-gpu-vector-adapters.ts +20 -7
  126. package/src/arrow/gpu/arrow-gpu-vector-conversion.ts +49 -6
  127. package/src/gpu-core/gpu-expression-operation.ts +1 -1
  128. package/src/gpu-core/gpu-graph-compiler.ts +61 -0
  129. package/src/gpu-core/gpu-group-aggregation.ts +38 -50
  130. package/src/gpu-core/gpu-reduction.ts +32 -42
  131. package/src/gpu-core/gpu-semantic-aggregation-operation.ts +150 -0
  132. package/src/gpu-core/index.ts +6 -0
  133. package/src/gpu-data/color-conversion.ts +158 -0
  134. package/src/gpu-data/cpu-gpu-vector-transfer.ts +10 -7
  135. package/src/gpu-data/gpu-data-buffer-props.ts +25 -0
  136. package/src/gpu-data/index.ts +3 -0
  137. package/src/gpu-graph/index.ts +9 -0
  138. package/src/gpu-simple-graph/index.ts +1 -0
  139. package/src/gpu-simple-graph/operation/gpu-data-evaluator.ts +2 -0
  140. package/src/gpu-simple-graph/operations/convert-colors.ts +22 -7
  141. package/src/gpu-simple-graph/operations/cpu/convert-colors.ts +31 -48
  142. package/src/gpu-simple-graph/operations/webgpu/convert-colors.ts +47 -13
  143. package/src/gpu-sql/gpu-sql.ts +130 -103
  144. package/src/gpu-tables/table/gpu-table.ts +2 -1
  145. package/src/index.ts +9 -0
package/dist/dist.dev.js CHANGED
@@ -68,6 +68,8 @@ var __exports__ = (() => {
68
68
  GPUExpressionOperation: () => GPUExpressionOperation,
69
69
  GPUGraph: () => GPUGraph,
70
70
  GPUGraphCompiler: () => GPUGraphCompiler,
71
+ GPUGraphGroupAggregation: () => GPUGraphGroupAggregation,
72
+ GPUGraphReduction: () => GPUGraphReduction,
71
73
  GPUGraphScalar: () => GPUGraphScalar,
72
74
  GPUGraphTexture: () => GPUGraphTexture,
73
75
  GPUGraphTextureView: () => GPUGraphTextureView,
@@ -710,7 +712,148 @@ var __exports__ = (() => {
710
712
  return `${id}-${count}`;
711
713
  }
712
714
 
715
+ // ../core/src/api/utils/assert.ts
716
+ function assert3(condition, message) {
717
+ if (!condition) {
718
+ const error = new Error(message ?? "luma.gl assertion failed.");
719
+ Error.captureStackTrace?.(error, assert3);
720
+ throw error;
721
+ }
722
+ }
723
+
713
724
  // ../core/src/api/adapter/resources/resource.ts
725
+ var Resource = class {
726
+ _owner = null;
727
+ _ownedResources = /* @__PURE__ */ new Set();
728
+ _state = "live";
729
+ _destroyingOwnedResources = false;
730
+ _destroyRequested = false;
731
+ /** The resource responsible for destroying this resource, or null for caller-managed lifetime. */
732
+ get owner() {
733
+ return this._owner;
734
+ }
735
+ /** A snapshot of this resource's children. Mutating the snapshot cannot change ownership. */
736
+ get ownedResources() {
737
+ return Array.from(this._ownedResources);
738
+ }
739
+ /** Whether destruction has completed, including when cleanup reported an error. */
740
+ get destroyed() {
741
+ return this._state === "destroyed";
742
+ }
743
+ /** Transfer exclusive ownership, or return lifetime responsibility to the caller with null. */
744
+ transferOwnershipTo(owner) {
745
+ assert3(this._state === "live" && !this._destroyingOwnedResources);
746
+ assert3(!this._owner || this._owner.canChangeOwnership());
747
+ assert3(!owner || owner.canChangeOwnership());
748
+ for (let ancestor = owner; ancestor; ancestor = ancestor._owner) {
749
+ assert3(ancestor !== this);
750
+ }
751
+ if (owner !== this._owner) {
752
+ this._owner?._ownedResources.delete(this);
753
+ this._owner = owner;
754
+ owner?._ownedResources.add(this);
755
+ }
756
+ return this;
757
+ }
758
+ /** Destroy children before this resource. Subclasses implement hooks instead of overriding. */
759
+ destroy() {
760
+ if (this._state !== "live") {
761
+ return;
762
+ }
763
+ if (this._destroyingOwnedResources) {
764
+ this._destroyRequested = true;
765
+ return;
766
+ }
767
+ this._destroyRequested = false;
768
+ this._state = "destroying";
769
+ this._owner?._ownedResources.delete(this);
770
+ this._owner = null;
771
+ const errors = [];
772
+ try {
773
+ try {
774
+ this.onBeforeDestroy();
775
+ } catch (error) {
776
+ errors.push(error);
777
+ }
778
+ this.destroyChildren(errors);
779
+ try {
780
+ this.onDestroy();
781
+ } catch (error) {
782
+ errors.push(error);
783
+ }
784
+ } finally {
785
+ this._state = "destroyed";
786
+ }
787
+ if (errors.length) {
788
+ throw new AggregateError(errors, "Resource cleanup failed");
789
+ }
790
+ }
791
+ /** @deprecated Use destroy(). */
792
+ delete() {
793
+ this.destroy();
794
+ return this;
795
+ }
796
+ /** @deprecated Use resource.transferOwnershipTo(this). */
797
+ attachResource(resource) {
798
+ resource.transferOwnershipTo(this);
799
+ }
800
+ /** @deprecated Use resource.transferOwnershipTo(null). Only detaches a child owned by this. */
801
+ detachResource(resource) {
802
+ if (resource._owner === this) {
803
+ resource.transferOwnershipTo(null);
804
+ }
805
+ }
806
+ /** @deprecated Check resource.owner and call resource.destroy(). */
807
+ destroyAttachedResource(resource) {
808
+ if (resource._owner === this) {
809
+ resource.destroy();
810
+ }
811
+ }
812
+ /** @deprecated Destroy individually owned resources, or destroy the owner. */
813
+ destroyAttachedResources() {
814
+ if (this._state !== "live" || this._destroyingOwnedResources) {
815
+ return;
816
+ }
817
+ const errors = [];
818
+ this.destroyChildren(errors);
819
+ if (this._destroyRequested) {
820
+ try {
821
+ this.destroy();
822
+ } catch (error) {
823
+ errors.push(error);
824
+ }
825
+ }
826
+ if (errors.length) {
827
+ throw new AggregateError(errors, "Resource cleanup failed");
828
+ }
829
+ }
830
+ /** Stop activity before children are destroyed. Errors are collected; this hook cannot veto cleanup. */
831
+ onBeforeDestroy() {
832
+ }
833
+ /** Release this resource's own state after its children have been destroyed. */
834
+ onDestroy() {
835
+ }
836
+ canChangeOwnership() {
837
+ return this._state === "live" && !this._destroyingOwnedResources;
838
+ }
839
+ destroyChildren(errors) {
840
+ this._destroyingOwnedResources = true;
841
+ try {
842
+ for (const resource of this._ownedResources) {
843
+ try {
844
+ resource.destroy();
845
+ } catch (error) {
846
+ errors.push(error);
847
+ }
848
+ }
849
+ } finally {
850
+ this._ownedResources.clear();
851
+ this._destroyingOwnedResources = false;
852
+ }
853
+ }
854
+ };
855
+
856
+ // ../core/src/api/adapter/resources/device-resource.ts
714
857
  var CPU_HOTSPOT_PROFILER_MODULE = "cpu-hotspot-profiler";
715
858
  var RESOURCE_COUNTS_STATS = "GPU Resource Counts";
716
859
  var LEGACY_RESOURCE_COUNTS_STATS = "Resource Counts";
@@ -766,7 +909,7 @@ var __exports__ = (() => {
766
909
  ]);
767
910
  var ORDERED_STATS_CACHE = /* @__PURE__ */ new WeakMap();
768
911
  var ORDERED_STAT_NAME_SET_CACHE = /* @__PURE__ */ new WeakMap();
769
- var Resource = class {
912
+ var DeviceResource = class extends Resource {
770
913
  /** Default properties for resource */
771
914
  static defaultProps = {
772
915
  id: "undefined",
@@ -789,14 +932,10 @@ var __exports__ = (() => {
789
932
  userData = {};
790
933
  /** The device that this resource is associated with - TODO can we remove this dup? */
791
934
  _device;
792
- /** Whether this resource has been destroyed */
793
- destroyed = false;
794
935
  /** For resources that allocate GPU memory */
795
936
  allocatedBytes = 0;
796
937
  /** Stats bucket currently holding the tracked allocation */
797
938
  allocatedBytesName = null;
798
- /** Attached resources will be destroyed when this resource is destroyed. Tracks auto-created "sub" resources. */
799
- _attachedResources = /* @__PURE__ */ new Set();
800
939
  /** Whether luma.gl created and owns the underlying resource handle. */
801
940
  get ownsHandle() {
802
941
  return (this.props.handle === void 0 || this.props.handle === null) && !this.isHandleBorrowed;
@@ -806,9 +945,10 @@ var __exports__ = (() => {
806
945
  return Boolean(this.props._isHandleBorrowed);
807
946
  }
808
947
  /**
809
- * Create a new Resource. Called from Subclass
948
+ * Create a new DeviceResource. Called from Subclass
810
949
  */
811
950
  constructor(device, props, defaultProps) {
951
+ super();
812
952
  if (!device) {
813
953
  throw new Error("no device");
814
954
  }
@@ -820,20 +960,6 @@ var __exports__ = (() => {
820
960
  this.userData = this.props.userData || {};
821
961
  this.addStats();
822
962
  }
823
- /**
824
- * destroy can be called on any resource to release it before it is garbage collected.
825
- */
826
- destroy() {
827
- if (this.destroyed) {
828
- return;
829
- }
830
- this.destroyResource();
831
- }
832
- /** @deprecated Use destroy() */
833
- delete() {
834
- this.destroy();
835
- return this;
836
- }
837
963
  /**
838
964
  * Combines a map of user props and default props, only including props from defaultProps
839
965
  * @returns returns a map of overridden default props
@@ -841,46 +967,19 @@ var __exports__ = (() => {
841
967
  getProps() {
842
968
  return this.props;
843
969
  }
844
- // ATTACHED RESOURCES
845
- /**
846
- * Attaches a resource. Attached resources are auto destroyed when this resource is destroyed
847
- * Called automatically when sub resources are auto created but can be called by application
848
- */
849
- attachResource(resource) {
850
- this._attachedResources.add(resource);
851
- }
852
- /**
853
- * Detach an attached resource. The resource will no longer be auto-destroyed when this resource is destroyed.
854
- */
855
- detachResource(resource) {
856
- this._attachedResources.delete(resource);
857
- }
858
- /**
859
- * Destroys a resource (only if owned), and removes from the owned (auto-destroy) list for this resource.
860
- */
861
- destroyAttachedResource(resource) {
862
- if (this._attachedResources.delete(resource)) {
863
- resource.destroy();
864
- }
865
- }
866
- /** Destroy all owned resources. Make sure the resources are no longer needed before calling. */
867
- destroyAttachedResources() {
868
- for (const resource of this._attachedResources) {
869
- resource.destroy();
870
- }
871
- this._attachedResources = /* @__PURE__ */ new Set();
970
+ /** Backend cleanup. Override this instead of destroy(); children are already destroyed. */
971
+ destroyHandle() {
872
972
  }
873
- // PROTECTED METHODS
874
- /** Perform all destroy steps. Can be called by derived resources when overriding destroy() */
875
- destroyResource() {
876
- if (this.destroyed) {
877
- return;
973
+ /** Complete device bookkeeping even when backend cleanup fails. */
974
+ onDestroy() {
975
+ try {
976
+ this.destroyHandle();
977
+ } finally {
978
+ this.trackDeallocatedMemory();
979
+ this.removeStats();
878
980
  }
879
- this.destroyAttachedResources();
880
- this.removeStats();
881
- this.destroyed = true;
882
981
  }
883
- /** Called by .destroy() to track object destruction. Subclass must call if overriding destroy() */
982
+ /** Track object destruction after backend cleanup. */
884
983
  removeStats() {
885
984
  const profiler = getCpuHotspotProfiler(this._device);
886
985
  const startTime = profiler ? getTimestamp() : 0;
@@ -1058,7 +1157,7 @@ var __exports__ = (() => {
1058
1157
  let prototype = Object.getPrototypeOf(resource);
1059
1158
  while (prototype) {
1060
1159
  const parentPrototype = Object.getPrototypeOf(prototype);
1061
- if (!parentPrototype || parentPrototype === Resource.prototype) {
1160
+ if (!parentPrototype || parentPrototype === DeviceResource.prototype) {
1062
1161
  return getPrototypeToStringTag(prototype) || resource[Symbol.toStringTag] || resource.constructor.name;
1063
1162
  }
1064
1163
  prototype = parentPrototype;
@@ -1077,7 +1176,7 @@ var __exports__ = (() => {
1077
1176
  }
1078
1177
 
1079
1178
  // ../core/src/api/adapter/resources/buffer.ts
1080
- var Buffer3 = class _Buffer extends Resource {
1179
+ var Buffer3 = class _Buffer extends DeviceResource {
1081
1180
  /** Index buffer */
1082
1181
  static INDEX = 16;
1083
1182
  /** Vertex buffer */
@@ -1158,7 +1257,7 @@ var __exports__ = (() => {
1158
1257
  }
1159
1258
  }
1160
1259
  static defaultProps = {
1161
- ...Resource.defaultProps,
1260
+ ...DeviceResource.defaultProps,
1162
1261
  handle: void 0,
1163
1262
  usage: 0,
1164
1263
  // Buffer.COPY_DST | Buffer.COPY_SRC
@@ -1746,9 +1845,9 @@ var __exports__ = (() => {
1746
1845
  }
1747
1846
 
1748
1847
  // ../core/src/api/adapter/resources/sampler.ts
1749
- var Sampler = class _Sampler extends Resource {
1848
+ var Sampler = class _Sampler extends DeviceResource {
1750
1849
  static defaultProps = {
1751
- ...Resource.defaultProps,
1850
+ ...DeviceResource.defaultProps,
1752
1851
  type: "color-sampler",
1753
1852
  addressModeU: "clamp-to-edge",
1754
1853
  addressModeV: "clamp-to-edge",
@@ -1773,6 +1872,20 @@ var __exports__ = (() => {
1773
1872
  return props;
1774
1873
  }
1775
1874
  };
1875
+ function setTextureSampler(texture, sampler) {
1876
+ const nextSampler = sampler instanceof Sampler ? sampler : texture.device.createSampler(sampler);
1877
+ if (nextSampler === texture.sampler) {
1878
+ return;
1879
+ }
1880
+ if (!(sampler instanceof Sampler)) {
1881
+ nextSampler.transferOwnershipTo(texture);
1882
+ }
1883
+ const previousSampler = texture.sampler;
1884
+ texture.sampler = nextSampler;
1885
+ if (previousSampler?.owner === texture) {
1886
+ previousSampler.destroy();
1887
+ }
1888
+ }
1776
1889
 
1777
1890
  // ../core/src/api/adapter/resources/texture.ts
1778
1891
  var textureLayoutScratchPool = [];
@@ -1785,7 +1898,7 @@ var __exports__ = (() => {
1785
1898
  "cube-array": "2d",
1786
1899
  "3d": "3d"
1787
1900
  };
1788
- var Texture2 = class _Texture extends Resource {
1901
+ var Texture2 = class _Texture extends DeviceResource {
1789
1902
  /** The texture can be bound for use as a sampled texture in a shader */
1790
1903
  static SAMPLE = 4;
1791
1904
  /** The texture can be bound for use as a storage texture in a shader */
@@ -1873,7 +1986,7 @@ var __exports__ = (() => {
1873
1986
  }
1874
1987
  /** Set sampler props associated with this texture */
1875
1988
  setSampler(sampler) {
1876
- this.sampler = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);
1989
+ setTextureSampler(this, sampler);
1877
1990
  }
1878
1991
  /**
1879
1992
  * Copy raw image data (bytes) into the texture.
@@ -2181,7 +2294,7 @@ var __exports__ = (() => {
2181
2294
  return result;
2182
2295
  }
2183
2296
  static defaultProps = {
2184
- ...Resource.defaultProps,
2297
+ ...DeviceResource.defaultProps,
2185
2298
  data: null,
2186
2299
  dimension: "2d",
2187
2300
  format: "rgba8unorm",
@@ -7170,6 +7283,52 @@ var __exports__ = (() => {
7170
7283
  }
7171
7284
  };
7172
7285
 
7286
+ // src/gpu-core/graph-vector-view-utils.ts
7287
+ function getGraphVectorData(vector) {
7288
+ return vector instanceof GraphVectorView ? vector.data : [vector];
7289
+ }
7290
+ function alignGraphVectorViews(graph, vectors) {
7291
+ const length = vectors[0]?.length ?? 0;
7292
+ if (vectors.some((vector) => vector.length !== length)) {
7293
+ throw new Error("Aligned vectors must have equal logical lengths");
7294
+ }
7295
+ const chunks = vectors.map(getGraphVectorData);
7296
+ const indices = vectors.map(() => 0);
7297
+ const offsets = vectors.map(() => 0);
7298
+ const result = [];
7299
+ let position = 0;
7300
+ while (position < length) {
7301
+ for (let index = 0; index < chunks.length; index++) {
7302
+ while (chunks[index][indices[index]]?.length === offsets[index]) {
7303
+ indices[index]++;
7304
+ offsets[index] = 0;
7305
+ }
7306
+ }
7307
+ const current = chunks.map((data, index) => data[indices[index]]);
7308
+ const span = Math.min(...current.map((data, index) => data.length - offsets[index]));
7309
+ const aligned = [];
7310
+ for (let index = 0; index < current.length; index++) {
7311
+ const data = current[index];
7312
+ const matchingIndex = current.findIndex(
7313
+ (candidate, candidateIndex) => candidateIndex < index && candidate === data && offsets[candidateIndex] === offsets[index]
7314
+ );
7315
+ aligned.push(
7316
+ matchingIndex >= 0 ? aligned[matchingIndex] : offsets[index] === 0 && span === data.length ? data : graph.createDataView(data.buffer, {
7317
+ format: data.format,
7318
+ length: span,
7319
+ byteOffset: data.byteOffset + offsets[index] * data.byteStride,
7320
+ byteStride: data.byteStride,
7321
+ rowByteLength: data.rowByteLength
7322
+ })
7323
+ );
7324
+ }
7325
+ result.push(aligned);
7326
+ for (let index = 0; index < offsets.length; index++) offsets[index] += span;
7327
+ position += span;
7328
+ }
7329
+ return result;
7330
+ }
7331
+
7173
7332
  // src/gpu-core/gpu-command-dispatch-metadata.ts
7174
7333
  function setGPUComputeDispatchWorkgroups(node, workgroups) {
7175
7334
  const [x, y, z] = workgroups;
@@ -7380,101 +7539,1127 @@ var __exports__ = (() => {
7380
7539
  emptyChunk ??= createTransientView(graph, `${id}-empty`, template.format, 0);
7381
7540
  return emptyChunk;
7382
7541
  }
7383
- return createTransientView(graph, `${id}-chunk-${chunkIndex}`, template.format, chunk.length);
7384
- });
7385
- return new GraphVectorView({
7386
- id,
7387
- name: id,
7388
- format: template.format,
7389
- length: template.length,
7390
- valueLength: template.valueLength,
7391
- stride: template.stride,
7392
- byteStride: template.byteStride,
7393
- rowByteLength: template.rowByteLength,
7394
- data
7395
- });
7396
- }
7397
- function getGraphDataPrefix(graph, input, length) {
7398
- if (!Number.isSafeInteger(length) || length < 0 || length > input.length) {
7399
- throw new Error("Graph prefix must fit within the input");
7542
+ return createTransientView(graph, `${id}-chunk-${chunkIndex}`, template.format, chunk.length);
7543
+ });
7544
+ return new GraphVectorView({
7545
+ id,
7546
+ name: id,
7547
+ format: template.format,
7548
+ length: template.length,
7549
+ valueLength: template.valueLength,
7550
+ stride: template.stride,
7551
+ byteStride: template.byteStride,
7552
+ rowByteLength: template.rowByteLength,
7553
+ data
7554
+ });
7555
+ }
7556
+ function getGraphDataPrefix(graph, input, length) {
7557
+ if (!Number.isSafeInteger(length) || length < 0 || length > input.length) {
7558
+ throw new Error("Graph prefix must fit within the input");
7559
+ }
7560
+ if (length === input.length) return input;
7561
+ const chunks = input instanceof GraphVectorView ? input.data : [input];
7562
+ let remaining = length;
7563
+ const data = [];
7564
+ for (const chunk of chunks) {
7565
+ const chunkLength = Math.min(remaining, chunk.length);
7566
+ data.push(
7567
+ chunkLength === chunk.length ? chunk : graph.createDataView(chunk.buffer, {
7568
+ format: chunk.format,
7569
+ length: chunkLength,
7570
+ byteOffset: chunk.byteOffset,
7571
+ byteStride: chunk.byteStride,
7572
+ rowByteLength: chunk.rowByteLength
7573
+ })
7574
+ );
7575
+ remaining -= chunkLength;
7576
+ if (remaining === 0) break;
7577
+ }
7578
+ return input instanceof GraphVectorView ? new GraphVectorView({
7579
+ ...input,
7580
+ length,
7581
+ valueLength: length * (getGPUVectorFormatInfo(input.format).listSize ?? 1),
7582
+ data
7583
+ }) : data[0];
7584
+ }
7585
+
7586
+ // src/gpu-core/gpu-subgroup-utils.ts
7587
+ function getGPUShaderSubgroupStrategy(device, options = {}) {
7588
+ const supportsSubgroups = device.features?.has("subgroups");
7589
+ const supportsRequiredLanguageFeatures = !options.requiresSubgroupId || device.wgslLanguageFeatures?.has("subgroup_id");
7590
+ return supportsSubgroups && supportsRequiredLanguageFeatures ? "subgroups" : "portable";
7591
+ }
7592
+ function getSubgroupBallotHelpersWGSL() {
7593
+ return (
7594
+ /* wgsl */
7595
+ `
7596
+ fn getFirstBallotLane(mask: vec4<u32>) -> u32 {
7597
+ if (mask.x != 0u) { return firstTrailingBit(mask.x); }
7598
+ if (mask.y != 0u) { return 32u + firstTrailingBit(mask.y); }
7599
+ if (mask.z != 0u) { return 64u + firstTrailingBit(mask.z); }
7600
+ if (mask.w != 0u) { return 96u + firstTrailingBit(mask.w); }
7601
+ return 0u;
7602
+ }
7603
+
7604
+ fn getBallotLaneCount(mask: vec4<u32>) -> u32 {
7605
+ return countOneBits(mask.x) + countOneBits(mask.y) +
7606
+ countOneBits(mask.z) + countOneBits(mask.w);
7607
+ }
7608
+
7609
+ fn getBallotPrefixLaneCount(mask: vec4<u32>, invocation: u32) -> u32 {
7610
+ let word = invocation >> 5u;
7611
+ let bit = invocation & 31u;
7612
+ var count = 0u;
7613
+ if (word > 0u) { count += countOneBits(mask.x); }
7614
+ if (word > 1u) { count += countOneBits(mask.y); }
7615
+ if (word > 2u) { count += countOneBits(mask.z); }
7616
+ let lowerBits = (1u << bit) - 1u;
7617
+ return count + countOneBits(mask[word] & lowerBits);
7618
+ }`
7619
+ );
7620
+ }
7621
+ function getSubgroupCoalescedAtomicAddWGSL(acceptedExpression, keyExpression, atomicArrayName, maximumDistinctKeyCount) {
7622
+ return (
7623
+ /* wgsl */
7624
+ `
7625
+ var subgroupPending = ${acceptedExpression};
7626
+ for (var subgroupGroup = 0u; subgroupGroup < ${maximumDistinctKeyCount}u; subgroupGroup++) {
7627
+ let pendingBallot = subgroupBallot(subgroupPending);
7628
+ let hasPending = any(pendingBallot != vec4<u32>(0u));
7629
+ let leaderInvocation = getFirstBallotLane(pendingBallot);
7630
+ let leaderKey = subgroupShuffle(${keyExpression}, leaderInvocation);
7631
+ let matchingKey = hasPending && subgroupPending && ${keyExpression} == leaderKey;
7632
+ let matchingBallot = subgroupBallot(matchingKey);
7633
+ if (hasPending && subgroupInvocationId == leaderInvocation) {
7634
+ atomicAdd(&${atomicArrayName}[leaderKey], getBallotLaneCount(matchingBallot));
7635
+ }
7636
+ subgroupPending = subgroupPending && !matchingKey;
7637
+ }`
7638
+ );
7639
+ }
7640
+
7641
+ // src/gpu-core/gpu-group-aggregation.ts
7642
+ var GROUP_AGGREGATION_WORKGROUP_SIZE = 256;
7643
+ var MAXIMUM_LOCAL_GROUP_COUNT = 256;
7644
+ var MAXIMUM_SUBGROUP_COALESCED_GROUP_COUNT = 16;
7645
+ var UINT32_BYTE_LENGTH3 = Uint32Array.BYTES_PER_ELEMENT;
7646
+ var GPUGroupAggregation = class {
7647
+ /** Prefix for generated graph node IDs. */
7648
+ id;
7649
+ /** Packed group keys or ordered group-key vector. */
7650
+ keys;
7651
+ /** Optional packed values with the same logical length as keys. */
7652
+ values;
7653
+ /** Caller-owned dense group result. */
7654
+ output;
7655
+ /** Optional source-aligned row selection. */
7656
+ mask;
7657
+ /** Group statistic computed by this aggregation. */
7658
+ operation;
7659
+ /** Creates and validates a dense group-aggregation description. */
7660
+ constructor(props) {
7661
+ this.id = props.id ?? "gpu-group-aggregation";
7662
+ this.keys = props.keys;
7663
+ this.values = props.values;
7664
+ this.output = props.output;
7665
+ this.mask = props.mask;
7666
+ this.operation = props.operation ?? "count";
7667
+ for (const [chunkIndex, chunk] of getGroupChunks(this.keys).entries()) {
7668
+ validateScalarInputView(chunk, "uint32", `${this.id} keys chunk ${chunkIndex}`);
7669
+ }
7670
+ if (this.output.length === 0) {
7671
+ throw new Error(`${this.id} output must contain at least one group`);
7672
+ }
7673
+ if (!["count", "sum", "min", "max", "mean"].includes(this.operation)) {
7674
+ throw new Error(`${this.id} operation must be count, sum, min, max, or mean`);
7675
+ }
7676
+ if (this.operation === "count") {
7677
+ validatePackedUint32View(this.output, `${this.id} count output`);
7678
+ if (this.values) {
7679
+ throw new Error(`${this.id} count operation must not provide values`);
7680
+ }
7681
+ } else {
7682
+ validatePackedView(this.output, ["float32"], `${this.id} statistic output`);
7683
+ if (!this.values) {
7684
+ throw new Error(`${this.id} ${this.operation} operation requires values`);
7685
+ }
7686
+ for (const [chunkIndex, chunk] of getValueChunks(this.values).entries()) {
7687
+ validateScalarInputView(chunk, "float32", `${this.id} values chunk ${chunkIndex}`);
7688
+ }
7689
+ validateMatchingInputs(this.keys, this.values, `${this.id} keys and values`);
7690
+ if (this.operation === "mean" && this.keys.length > 4294967295) {
7691
+ throw new Error(`${this.id} mean input length must fit in uint32 group counts`);
7692
+ }
7693
+ }
7694
+ if (getGroupChunks(this.keys).some((chunk) => chunk.buffer === this.output.buffer)) {
7695
+ throw new Error(`${this.id} keys and output must use separate buffers`);
7696
+ }
7697
+ if (this.values && getValueChunks(this.values).some((chunk) => chunk.buffer === this.output.buffer)) {
7698
+ throw new Error(`${this.id} values and output must use separate buffers`);
7699
+ }
7700
+ if (this.mask) {
7701
+ for (const [chunkIndex, chunk] of getGroupChunks(this.mask).entries()) {
7702
+ validateScalarInputView(chunk, "uint32", `${this.id} mask chunk ${chunkIndex}`);
7703
+ if (chunk.buffer === this.output.buffer) {
7704
+ throw new Error(`${this.id} mask and output must use separate buffers`);
7705
+ }
7706
+ }
7707
+ validateMatchingInputs(this.keys, this.mask, `${this.id} keys and mask`);
7708
+ }
7709
+ }
7710
+ /**
7711
+ * Adds initialization, one accumulation pass per non-empty source chunk, and any required
7712
+ * finalization.
7713
+ *
7714
+ * This method declares work only and does not submit or read back commands.
7715
+ */
7716
+ getCommandNodes(graph) {
7717
+ const nodes = [];
7718
+ let keyChunks = getGroupChunks(this.keys);
7719
+ let maskChunks = this.mask ? getGroupChunks(this.mask) : void 0;
7720
+ let valueChunks = this.values ? getValueChunks(this.values) : void 0;
7721
+ if (keyChunks.some((chunk) => chunk.buffer.graph !== graph) || maskChunks?.some((chunk) => chunk.buffer.graph !== graph) || valueChunks?.some((chunk) => chunk.buffer.graph !== graph) || this.output.buffer.graph !== graph) {
7722
+ throw new Error(`${this.id} views must belong to the target graph`);
7723
+ }
7724
+ if (this.values) {
7725
+ const spans = alignGraphVectorViews(graph, [this.keys, this.values, this.mask ?? this.keys]);
7726
+ keyChunks = spans.map(([keys]) => keys);
7727
+ valueChunks = spans.map(([, values]) => values);
7728
+ maskChunks = this.mask ? spans.map(([, , mask]) => mask) : void 0;
7729
+ } else if (this.mask) {
7730
+ const spans = alignGraphVectorViews(graph, [this.keys, this.mask]);
7731
+ keyChunks = spans.map(([keys]) => keys);
7732
+ maskChunks = spans.map(([, mask]) => mask);
7733
+ }
7734
+ if (this.operation === "count") {
7735
+ const output2 = this.output;
7736
+ nodes.push(...addClearGroupsPass(graph, this.id, output2));
7737
+ const accumulationPath = output2.length <= MAXIMUM_LOCAL_GROUP_COUNT ? "local" : "global";
7738
+ for (let chunkIndex = 0; chunkIndex < keyChunks.length; chunkIndex++) {
7739
+ const keys = keyChunks[chunkIndex];
7740
+ if (keys.length === 0) continue;
7741
+ nodes.push(
7742
+ ...addGroupCountPass(graph, {
7743
+ id: this.keys instanceof GraphVectorView || keyChunks.length > 1 ? `${this.id}-chunk-${chunkIndex}-${accumulationPath}` : `${this.id}-${accumulationPath}`,
7744
+ keys,
7745
+ output: output2,
7746
+ mask: maskChunks?.[chunkIndex],
7747
+ dispatchLayout: getGPUGroupAggregationDispatchLayout(
7748
+ keys.length,
7749
+ graph.device.limits.maxComputeWorkgroupsPerDimension
7750
+ )
7751
+ })
7752
+ );
7753
+ }
7754
+ return nodes;
7755
+ }
7756
+ const output = this.output;
7757
+ const operation = this.operation;
7758
+ const counts = operation === "mean" ? createTransientView(graph, `${this.id}-counts`, "uint32", output.length) : void 0;
7759
+ nodes.push(...addInitializeGroupStatisticsPass(graph, this.id, output, operation, counts));
7760
+ for (let chunkIndex = 0; chunkIndex < keyChunks.length; chunkIndex++) {
7761
+ const keys = keyChunks[chunkIndex];
7762
+ if (keys.length === 0) continue;
7763
+ nodes.push(
7764
+ ...addGroupStatisticPass(graph, {
7765
+ id: this.keys instanceof GraphVectorView || keyChunks.length > 1 ? `${this.id}-chunk-${chunkIndex}` : this.id,
7766
+ keys,
7767
+ values: valueChunks[chunkIndex],
7768
+ mask: maskChunks?.[chunkIndex],
7769
+ output,
7770
+ operation,
7771
+ counts,
7772
+ dispatchLayout: getGPUGroupAggregationDispatchLayout(
7773
+ keys.length,
7774
+ graph.device.limits.maxComputeWorkgroupsPerDimension
7775
+ )
7776
+ })
7777
+ );
7778
+ }
7779
+ if (operation !== "sum") {
7780
+ nodes.push(...addFinalizeGroupStatisticsPass(graph, this.id, output, operation, counts));
7781
+ }
7782
+ return nodes;
7783
+ }
7784
+ };
7785
+ function validateScalarInputView(view, format, name) {
7786
+ if (view.format !== format || view.rowByteLength !== UINT32_BYTE_LENGTH3 || view.byteStride < UINT32_BYTE_LENGTH3 || view.byteStride % UINT32_BYTE_LENGTH3 !== 0 || view.byteOffset % UINT32_BYTE_LENGTH3 !== 0) {
7787
+ throw new Error(`${name} must be a uint32-aligned scalar ${format} GPU data view`);
7788
+ }
7789
+ }
7790
+ function getScalarStride(view) {
7791
+ return view.byteStride / UINT32_BYTE_LENGTH3;
7792
+ }
7793
+ function getGroupChunks(input) {
7794
+ return input instanceof GraphVectorView ? input.data : [input];
7795
+ }
7796
+ function getValueChunks(input) {
7797
+ return input instanceof GraphVectorView ? input.data : [input];
7798
+ }
7799
+ function validateMatchingInputs(keys, paired, label) {
7800
+ if (keys.length !== paired.length) {
7801
+ throw new Error(`${label} lengths must match`);
7802
+ }
7803
+ }
7804
+ function addClearGroupsPass(graph, id, output) {
7805
+ const nodes = [];
7806
+ const dispatchLayout = getGPUGroupAggregationDispatchLayout(
7807
+ output.length,
7808
+ graph.device.limits.maxComputeWorkgroupsPerDimension
7809
+ );
7810
+ const source = (
7811
+ /* wgsl */
7812
+ `
7813
+ const GROUP_COUNT: u32 = ${output.length}u;
7814
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(output)}u;
7815
+ @group(0) @binding(0) var<storage, read_write> outputCounts: array<atomic<u32>>;
7816
+
7817
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE})
7818
+ fn main(
7819
+ @builtin(local_invocation_index) localInvocationIndex: u32,
7820
+ @builtin(workgroup_id) workgroupId: vec3<u32>
7821
+ ) {
7822
+ ${getBoundedInvocationIndexSource(dispatchLayout, GROUP_AGGREGATION_WORKGROUP_SIZE)}
7823
+ if (index < GROUP_COUNT) {
7824
+ atomicStore(&outputCounts[OUTPUT_OFFSET + index], 0u);
7825
+ }
7826
+ }`
7827
+ );
7828
+ nodes.push(
7829
+ ...addKernelPass(graph, {
7830
+ id: `${id}-clear`,
7831
+ source,
7832
+ resources: [{ buffer: output, usage: "storage-write" }],
7833
+ bindings: { outputCounts: output },
7834
+ dispatchSize: dispatchLayout
7835
+ })
7836
+ );
7837
+ return nodes;
7838
+ }
7839
+ function addGroupCountPass(graph, props) {
7840
+ const nodes = [];
7841
+ const local = props.output.length <= MAXIMUM_LOCAL_GROUP_COUNT;
7842
+ const useSubgroups = local && props.output.length <= MAXIMUM_SUBGROUP_COALESCED_GROUP_COUNT && getGPUShaderSubgroupStrategy(graph.device) === "subgroups";
7843
+ const maskBinding = props.mask ? "@group(0) @binding(1) var<storage, read> selectionMask: array<u32>;" : "";
7844
+ const outputBinding = props.mask ? 2 : 1;
7845
+ const maskCondition = props.mask ? `selectionMask[${getViewElementOffset(props.mask)}u + index * ${getScalarStride(props.mask)}u] != 0u` : "true";
7846
+ const localAccumulation = useSubgroups ? getSubgroupCoalescedAtomicAddWGSL(
7847
+ "accepted",
7848
+ "groupIndex",
7849
+ "localCounts",
7850
+ props.output.length
7851
+ ) : " if (accepted) { atomicAdd(&localCounts[groupIndex], 1u); }";
7852
+ const accumulation = local ? `${localAccumulation}
7853
+ workgroupBarrier();
7854
+ if (lane < GROUP_COUNT) {
7855
+ atomicAdd(&outputCounts[OUTPUT_OFFSET + lane], atomicLoad(&localCounts[lane]));
7856
+ }` : "if (accepted) { atomicAdd(&outputCounts[OUTPUT_OFFSET + groupIndex], 1u); }";
7857
+ const source = (
7858
+ /* wgsl */
7859
+ `
7860
+ ${useSubgroups ? "enable subgroups;" : ""}
7861
+ const ELEMENT_COUNT: u32 = ${props.keys.length}u;
7862
+ const GROUP_COUNT: u32 = ${props.output.length}u;
7863
+ const KEYS_OFFSET: u32 = ${getViewElementOffset(props.keys)}u;
7864
+ const KEYS_STRIDE: u32 = ${getScalarStride(props.keys)}u;
7865
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(props.output)}u;
7866
+ @group(0) @binding(0) var<storage, read> groupKeys: array<u32>;
7867
+ ${maskBinding}
7868
+ @group(0) @binding(${outputBinding}) var<storage, read_write> outputCounts: array<atomic<u32>>;
7869
+ ${local ? `var<workgroup> localCounts: array<atomic<u32>, ${props.output.length}>;` : ""}
7870
+ ${useSubgroups ? getSubgroupBallotHelpersWGSL() : ""}
7871
+
7872
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE}) fn main(
7873
+ @builtin(workgroup_id) workgroupId: vec3<u32>,
7874
+ @builtin(local_invocation_id) localId: vec3<u32>${useSubgroups ? ",\n @builtin(subgroup_invocation_id) subgroupInvocationId: u32" : ""}
7875
+ ) {
7876
+ let workgroupIndex = (workgroupId.z * ${props.dispatchLayout.y}u + workgroupId.y) * ${props.dispatchLayout.x}u + workgroupId.x;
7877
+ let index = workgroupIndex * ${GROUP_AGGREGATION_WORKGROUP_SIZE}u + localId.x;
7878
+ let lane = localId.x;
7879
+ ${local ? "if (lane < GROUP_COUNT) { atomicStore(&localCounts[lane], 0u); }\n workgroupBarrier();" : ""}
7880
+ var accepted = false;
7881
+ var groupIndex = 0u;
7882
+ if (index < ELEMENT_COUNT && ${maskCondition}) {
7883
+ groupIndex = groupKeys[KEYS_OFFSET + index * KEYS_STRIDE];
7884
+ accepted = groupIndex < GROUP_COUNT;
7885
+ }
7886
+ ${accumulation}
7887
+ }`
7888
+ );
7889
+ const resources = [
7890
+ { buffer: props.keys, usage: "storage-read" },
7891
+ ...props.mask ? [{ buffer: props.mask, usage: "storage-read" }] : [],
7892
+ { buffer: props.output, usage: "storage-read-write" }
7893
+ ];
7894
+ nodes.push(
7895
+ ...addKernelPass(graph, {
7896
+ id: props.id,
7897
+ source,
7898
+ resources,
7899
+ bindings: {
7900
+ groupKeys: props.keys,
7901
+ ...props.mask ? { selectionMask: props.mask } : {},
7902
+ outputCounts: props.output
7903
+ },
7904
+ dispatchSize: props.dispatchLayout
7905
+ })
7906
+ );
7907
+ return nodes;
7908
+ }
7909
+ function addInitializeGroupStatisticsPass(graph, id, output, operation, counts) {
7910
+ const nodes = [];
7911
+ const dispatchLayout = getGPUGroupAggregationDispatchLayout(
7912
+ output.length,
7913
+ graph.device.limits.maxComputeWorkgroupsPerDimension
7914
+ );
7915
+ const initialBits = operation === "min" ? "0xffffffffu" : "0u";
7916
+ const countBinding = counts ? "@group(0) @binding(1) var<storage, read_write> outputCounts: array<atomic<u32>>;" : "";
7917
+ const countInitialization = counts ? `atomicStore(&outputCounts[${getViewElementOffset(counts)}u + index], 0u);` : "";
7918
+ const source = (
7919
+ /* wgsl */
7920
+ `
7921
+ const GROUP_COUNT: u32 = ${output.length}u;
7922
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(output)}u;
7923
+ @group(0) @binding(0) var<storage, read_write> outputValues: array<atomic<u32>>;
7924
+ ${countBinding}
7925
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE}) fn main(
7926
+ @builtin(local_invocation_index) localInvocationIndex: u32,
7927
+ @builtin(workgroup_id) workgroupId: vec3<u32>
7928
+ ) {
7929
+ ${getBoundedInvocationIndexSource(dispatchLayout, GROUP_AGGREGATION_WORKGROUP_SIZE)}
7930
+ if (index < GROUP_COUNT) {
7931
+ atomicStore(&outputValues[OUTPUT_OFFSET + index], ${initialBits});
7932
+ ${countInitialization}
7933
+ }
7934
+ }`
7935
+ );
7936
+ nodes.push(
7937
+ ...addKernelPass(graph, {
7938
+ id: operation === "sum" ? `${id}-clear` : `${id}-initialize`,
7939
+ source,
7940
+ resources: [
7941
+ { buffer: output, usage: "storage-write" },
7942
+ ...counts ? [{ buffer: counts, usage: "storage-write" }] : []
7943
+ ],
7944
+ bindings: { outputValues: output, ...counts ? { outputCounts: counts } : {} },
7945
+ dispatchSize: dispatchLayout
7946
+ })
7947
+ );
7948
+ return nodes;
7949
+ }
7950
+ function addGroupStatisticPass(graph, props) {
7951
+ const nodes = [];
7952
+ const useSubgroups = props.output.length <= MAXIMUM_SUBGROUP_COALESCED_GROUP_COUNT && getGPUShaderSubgroupStrategy(graph.device) === "subgroups";
7953
+ const maskBinding = props.mask ? "@group(0) @binding(2) var<storage, read> selectionMask: array<u32>;" : "";
7954
+ const outputBinding = props.mask ? 3 : 2;
7955
+ const countsBinding = props.counts ? `@group(0) @binding(${outputBinding + 1}) var<storage, read_write> outputCounts: array<atomic<u32>>;` : "";
7956
+ const maskCondition = props.mask ? `selectionMask[${getViewElementOffset(props.mask)}u + index * ${getScalarStride(props.mask)}u] != 0u` : "true";
7957
+ const accumulation = useSubgroups ? getSubgroupStatisticAggregationWGSL(props.operation, props.output.length, props.counts) : ` if (accepted) {
7958
+ ${getFloatAggregationCall(props.operation, "groupIndex")}
7959
+ ${props.counts ? `atomicAdd(&outputCounts[${getViewElementOffset(props.counts)}u + groupIndex], 1u);` : ""}
7960
+ }`;
7961
+ const source = (
7962
+ /* wgsl */
7963
+ `
7964
+ ${useSubgroups ? "enable subgroups;" : ""}
7965
+ const ELEMENT_COUNT: u32 = ${props.keys.length}u;
7966
+ const GROUP_COUNT: u32 = ${props.output.length}u;
7967
+ const KEYS_OFFSET: u32 = ${getViewElementOffset(props.keys)}u;
7968
+ const VALUES_OFFSET: u32 = ${getViewElementOffset(props.values)}u;
7969
+ const KEYS_STRIDE: u32 = ${getScalarStride(props.keys)}u;
7970
+ const VALUES_STRIDE: u32 = ${getScalarStride(props.values)}u;
7971
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(props.output)}u;
7972
+ @group(0) @binding(0) var<storage, read> groupKeys: array<u32>;
7973
+ @group(0) @binding(1) var<storage, read> inputValues: array<f32>;
7974
+ ${maskBinding}
7975
+ @group(0) @binding(${outputBinding}) var<storage, read_write> outputValues: array<atomic<u32>>;
7976
+ ${countsBinding}
7977
+
7978
+ ${getFloatAggregationFunction(props.operation)}
7979
+ ${useSubgroups ? getSubgroupBallotHelpersWGSL() : ""}
7980
+
7981
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE}) fn main(
7982
+ @builtin(workgroup_id) workgroupId: vec3<u32>,
7983
+ @builtin(local_invocation_id) localId: vec3<u32>${useSubgroups ? ",\n @builtin(subgroup_invocation_id) subgroupInvocationId: u32" : ""}
7984
+ ) {
7985
+ let workgroupIndex = (workgroupId.z * ${props.dispatchLayout.y}u + workgroupId.y) * ${props.dispatchLayout.x}u + workgroupId.x;
7986
+ let index = workgroupIndex * ${GROUP_AGGREGATION_WORKGROUP_SIZE}u + localId.x;
7987
+ var accepted = false;
7988
+ var groupIndex = 0u;
7989
+ var value = 0.0;
7990
+ if (index < ELEMENT_COUNT && ${maskCondition}) {
7991
+ groupIndex = groupKeys[KEYS_OFFSET + index * KEYS_STRIDE];
7992
+ value = inputValues[VALUES_OFFSET + index * VALUES_STRIDE];
7993
+ let finiteValue = value == value && abs(value) <= 3.402823466e+38;
7994
+ accepted = groupIndex < GROUP_COUNT && finiteValue;
7995
+ }
7996
+ ${accumulation}
7997
+ }`
7998
+ );
7999
+ const resources = [
8000
+ { buffer: props.keys, usage: "storage-read" },
8001
+ { buffer: props.values, usage: "storage-read" },
8002
+ ...props.mask ? [{ buffer: props.mask, usage: "storage-read" }] : [],
8003
+ { buffer: props.output, usage: "storage-read-write" },
8004
+ ...props.counts ? [{ buffer: props.counts, usage: "storage-read-write" }] : []
8005
+ ];
8006
+ nodes.push(
8007
+ ...addKernelPass(graph, {
8008
+ id: `${props.id}-${props.operation}`,
8009
+ source,
8010
+ resources,
8011
+ bindings: {
8012
+ groupKeys: props.keys,
8013
+ inputValues: props.values,
8014
+ ...props.mask ? { selectionMask: props.mask } : {},
8015
+ outputValues: props.output,
8016
+ ...props.counts ? { outputCounts: props.counts } : {}
8017
+ },
8018
+ dispatchSize: props.dispatchLayout
8019
+ })
8020
+ );
8021
+ return nodes;
8022
+ }
8023
+ function addFinalizeGroupStatisticsPass(graph, id, output, operation, counts) {
8024
+ const nodes = [];
8025
+ const dispatchLayout = getGPUGroupAggregationDispatchLayout(
8026
+ output.length,
8027
+ graph.device.limits.maxComputeWorkgroupsPerDimension
8028
+ );
8029
+ const countBinding = counts ? "@group(0) @binding(1) var<storage, read> outputCounts: array<u32>;" : "";
8030
+ const finalizeStatement = operation === "mean" ? `let count = outputCounts[${getViewElementOffset(counts)}u + index];
8031
+ if (count == 0u) {
8032
+ outputValues[OUTPUT_OFFSET + index] = 0x7fc00000u;
8033
+ } else {
8034
+ let sum = bitcast<f32>(outputValues[OUTPUT_OFFSET + index]);
8035
+ outputValues[OUTPUT_OFFSET + index] = bitcast<u32>(sum / f32(count));
8036
+ }` : `let orderedValue = outputValues[OUTPUT_OFFSET + index];
8037
+ if (orderedValue == ${operation === "min" ? "0xffffffffu" : "0u"}) {
8038
+ outputValues[OUTPUT_OFFSET + index] = 0x7fc00000u;
8039
+ } else {
8040
+ outputValues[OUTPUT_OFFSET + index] = bitcast<u32>(decodeOrderedFloat(orderedValue));
8041
+ }`;
8042
+ const decodeFunction = operation === "mean" ? "" : `fn decodeOrderedFloat(value: u32) -> f32 {
8043
+ let bits = select(~value, value ^ 0x80000000u, (value & 0x80000000u) != 0u);
8044
+ return bitcast<f32>(bits);
8045
+ }`;
8046
+ const source = (
8047
+ /* wgsl */
8048
+ `
8049
+ const GROUP_COUNT: u32 = ${output.length}u;
8050
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(output)}u;
8051
+ @group(0) @binding(0) var<storage, read_write> outputValues: array<u32>;
8052
+ ${countBinding}
8053
+ ${decodeFunction}
8054
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE}) fn main(
8055
+ @builtin(local_invocation_index) localInvocationIndex: u32,
8056
+ @builtin(workgroup_id) workgroupId: vec3<u32>
8057
+ ) {
8058
+ ${getBoundedInvocationIndexSource(dispatchLayout, GROUP_AGGREGATION_WORKGROUP_SIZE)}
8059
+ if (index < GROUP_COUNT) {
8060
+ ${finalizeStatement}
8061
+ }
8062
+ }`
8063
+ );
8064
+ nodes.push(
8065
+ ...addKernelPass(graph, {
8066
+ id: `${id}-finalize`,
8067
+ source,
8068
+ resources: [
8069
+ { buffer: output, usage: "storage-read-write" },
8070
+ ...counts ? [{ buffer: counts, usage: "storage-read" }] : []
8071
+ ],
8072
+ bindings: { outputValues: output, ...counts ? { outputCounts: counts } : {} },
8073
+ dispatchSize: dispatchLayout
8074
+ })
8075
+ );
8076
+ return nodes;
8077
+ }
8078
+ function getFloatAggregationFunction(operation) {
8079
+ if (operation === "min" || operation === "max") {
8080
+ return `fn encodeOrderedFloat(value: f32) -> u32 {
8081
+ let bits = bitcast<u32>(value);
8082
+ return select(bits ^ 0x80000000u, ~bits, (bits & 0x80000000u) != 0u);
8083
+ }`;
8084
+ }
8085
+ return `fn atomicAddFloat(destination: ptr<storage, atomic<u32>, read_write>, value: f32) {
8086
+ var oldBits = atomicLoad(destination);
8087
+ loop {
8088
+ let newBits = bitcast<u32>(bitcast<f32>(oldBits) + value);
8089
+ let result = atomicCompareExchangeWeak(destination, oldBits, newBits);
8090
+ if (result.exchanged) { break; }
8091
+ oldBits = result.old_value;
8092
+ }
8093
+ }`;
8094
+ }
8095
+ function getFloatAggregationCall(operation, groupIndex, valueExpression = "value") {
8096
+ if (operation === "min" || operation === "max") {
8097
+ const atomicOperation = operation === "min" ? "atomicMin" : "atomicMax";
8098
+ return `${atomicOperation}(&outputValues[OUTPUT_OFFSET + ${groupIndex}], encodeOrderedFloat(${valueExpression}));`;
8099
+ }
8100
+ return `atomicAddFloat(&outputValues[OUTPUT_OFFSET + ${groupIndex}], ${valueExpression});`;
8101
+ }
8102
+ function getSubgroupStatisticAggregationWGSL(operation, groupCount, counts) {
8103
+ const orderedOperation = operation === "min" || operation === "max";
8104
+ const selectedValue = orderedOperation ? `select(${operation === "min" ? "0xffffffffu" : "0u"}, encodeOrderedFloat(value), matchingKey)` : "select(0.0, value, matchingKey)";
8105
+ const collective = operation === "min" ? "subgroupMin(selectedValue)" : operation === "max" ? "subgroupMax(selectedValue)" : "subgroupAdd(selectedValue)";
8106
+ const aggregationCall = orderedOperation ? `${operation === "min" ? "atomicMin" : "atomicMax"}(&outputValues[OUTPUT_OFFSET + leaderKey], aggregatedValue);` : getFloatAggregationCall(operation, "leaderKey", "aggregatedValue");
8107
+ return (
8108
+ /* wgsl */
8109
+ `
8110
+ var subgroupPending = accepted;
8111
+ for (var subgroupGroup = 0u; subgroupGroup < ${groupCount}u; subgroupGroup++) {
8112
+ let pendingBallot = subgroupBallot(subgroupPending);
8113
+ let hasPending = any(pendingBallot != vec4<u32>(0u));
8114
+ let leaderInvocation = getFirstBallotLane(pendingBallot);
8115
+ let leaderKey = subgroupShuffle(groupIndex, leaderInvocation);
8116
+ let matchingKey = hasPending && subgroupPending && groupIndex == leaderKey;
8117
+ let matchingBallot = subgroupBallot(matchingKey);
8118
+ let selectedValue = ${selectedValue};
8119
+ let aggregatedValue = ${collective};
8120
+ if (hasPending && subgroupInvocationId == leaderInvocation) {
8121
+ ${aggregationCall}
8122
+ ${counts ? `atomicAdd(&outputCounts[${getViewElementOffset(counts)}u + leaderKey], getBallotLaneCount(matchingBallot));` : ""}
8123
+ }
8124
+ subgroupPending = subgroupPending && !matchingKey;
8125
+ }`
8126
+ );
8127
+ }
8128
+ function getGPUGroupAggregationDispatchLayout(elementCount, maxComputeWorkgroupsPerDimension) {
8129
+ return getBoundedDispatchLayout(
8130
+ "GPUGroupAggregation",
8131
+ elementCount,
8132
+ GROUP_AGGREGATION_WORKGROUP_SIZE,
8133
+ maxComputeWorkgroupsPerDimension
8134
+ );
8135
+ }
8136
+ function addKernelPass(graph, props) {
8137
+ const { x, y, z } = props.dispatchSize ?? { x: props.dispatchCount ?? 1, y: 1, z: 1 };
8138
+ const maximumWorkgroupCount = x * y * z;
8139
+ const node = createGPUComputeCommandNode({
8140
+ id: props.id,
8141
+ resources: props.resources,
8142
+ workload: {
8143
+ operation: "GPUGroupAggregation",
8144
+ commandCount: 1,
8145
+ maximumWorkgroupCount,
8146
+ maximumInvocationCount: maximumWorkgroupCount * GROUP_AGGREGATION_WORKGROUP_SIZE
8147
+ },
8148
+ compile: ({ device }) => {
8149
+ const kernel = new Kernel(device, {
8150
+ id: props.id,
8151
+ source: props.source,
8152
+ shaderLayout: {
8153
+ bindings: Object.keys(props.bindings).map((name, location) => ({
8154
+ name,
8155
+ type: "storage",
8156
+ group: 0,
8157
+ location
8158
+ }))
8159
+ }
8160
+ });
8161
+ return {
8162
+ encode: ({ computePass, getBuffer }) => {
8163
+ const bindings = {};
8164
+ for (const [name, view] of Object.entries(props.bindings)) {
8165
+ bindings[name] = getViewBinding(view, getBuffer);
8166
+ }
8167
+ kernel.dispatch(computePass, { bindings, x, y, z });
8168
+ },
8169
+ destroy: () => kernel.destroy()
8170
+ };
8171
+ }
8172
+ });
8173
+ return [setGPUComputeDispatchWorkgroups(node, [x, y, z])];
8174
+ }
8175
+
8176
+ // src/gpu-core/gpu-reduction.ts
8177
+ var REDUCTION_WORKGROUP_SIZE = 256;
8178
+ var SCALAR_FORMATS = ["uint32", "sint32", "float32"];
8179
+ function getGPUReductionStrategy(device) {
8180
+ return getGPUShaderSubgroupStrategy(device, { requiresSubgroupId: true });
8181
+ }
8182
+ var GPUReduction = class {
8183
+ /** Prefix for generated graph node and transient resource IDs. */
8184
+ id;
8185
+ /** Scalar input chunk or vector. */
8186
+ input;
8187
+ /** Optional source-aligned row selection. */
8188
+ mask;
8189
+ /** Caller-owned result view. */
8190
+ output;
8191
+ /** Aggregate computed by this reduction. */
8192
+ operation;
8193
+ /**
8194
+ * Creates and validates a graph-native reduction description.
8195
+ *
8196
+ * @throws If views are not packed 32-bit scalar data, formats differ, the output has the wrong
8197
+ * length, or input and output use the same physical graph buffer.
8198
+ */
8199
+ constructor(props) {
8200
+ this.id = props.id ?? "gpu-reduction";
8201
+ this.input = props.input;
8202
+ this.mask = props.mask;
8203
+ this.output = props.output;
8204
+ this.operation = props.operation;
8205
+ for (const [chunkIndex, input] of getReductionInputs(this.input).entries()) {
8206
+ const name = this.input instanceof GraphVectorView ? ` input chunk ${chunkIndex}` : " input";
8207
+ validatePackedView(input, SCALAR_FORMATS, `${this.id}${name}`);
8208
+ if (input.format !== this.input.format) {
8209
+ throw new Error(`${this.id}${name} format must match the input format`);
8210
+ }
8211
+ }
8212
+ validatePackedView(this.output, SCALAR_FORMATS, `${this.id} output`);
8213
+ if (this.input.format !== this.output.format) {
8214
+ throw new Error(`${this.id} input and output formats must match`);
8215
+ }
8216
+ if (!["sum", "min", "max", "extent"].includes(this.operation)) {
8217
+ throw new Error(`${this.id} operation must be sum, min, max, or extent`);
8218
+ }
8219
+ const outputLength = this.operation === "extent" ? 2 : 1;
8220
+ if (this.output.length !== outputLength) {
8221
+ throw new Error(`${this.id} ${this.operation} output must contain ${outputLength} row(s)`);
8222
+ }
8223
+ if (getReductionInputs(this.input).some((input) => input.buffer === this.output.buffer)) {
8224
+ throw new Error(`${this.id} inputs and output must use separate buffers`);
8225
+ }
8226
+ if (this.mask) {
8227
+ for (const [chunkIndex, mask] of getReductionMasks(this.mask).entries()) {
8228
+ validatePackedUint32View(mask, `${this.id} mask chunk ${chunkIndex}`);
8229
+ if (mask.buffer === this.output.buffer) {
8230
+ throw new Error(`${this.id} mask and output must use separate buffers`);
8231
+ }
8232
+ }
8233
+ if (this.input.length !== this.mask.length) {
8234
+ throw new Error(`${this.id} input and mask lengths must match`);
8235
+ }
8236
+ }
8237
+ }
8238
+ /**
8239
+ * Adds hierarchical reduction passes and graph-owned scratch to a command graph.
8240
+ *
8241
+ * Empty inputs add a one-thread clear pass. A single non-empty chunk is reduced directly.
8242
+ * Multiple non-empty chunks are reduced independently, then their partial rows are merged. A
8243
+ * final pass converts an invalid floating-point min/max/extent result to zero and writes the
8244
+ * caller-owned output.
8245
+ *
8246
+ * @param graph Mutable graph that owns all input/output handles and generated scratch.
8247
+ */
8248
+ getCommandNodes(graph) {
8249
+ const nodes = [];
8250
+ let inputs = getReductionInputs(this.input);
8251
+ let masks = this.mask ? getReductionMasks(this.mask) : void 0;
8252
+ if (inputs.some((input) => input.buffer.graph !== graph) || masks?.some((mask) => mask.buffer.graph !== graph) || this.output.buffer.graph !== graph) {
8253
+ throw new Error(`${this.id} views must belong to the target graph`);
8254
+ }
8255
+ if (this.mask) {
8256
+ const spans = alignGraphVectorViews(graph, [this.input, this.mask]);
8257
+ inputs = spans.map(([input]) => input);
8258
+ masks = spans.map(([, mask]) => mask);
8259
+ }
8260
+ const nonEmptyInputs = inputs.map((input, chunkIndex) => ({ input, mask: masks?.[chunkIndex] })).filter(({ input }) => input.length > 0);
8261
+ if (nonEmptyInputs.length === 0) {
8262
+ nodes.push(...addClearReductionPass(graph, this.id, this.output));
8263
+ return nodes;
8264
+ }
8265
+ const valuesPerRow = this.operation === "extent" ? 2 : 1;
8266
+ const needsValidity = this.operation !== "sum" && (this.input.format === "float32" || Boolean(this.mask));
8267
+ let reductionResult;
8268
+ if (nonEmptyInputs.length === 1) {
8269
+ reductionResult = addReductionLevels(graph, {
8270
+ id: this.id,
8271
+ format: this.input.format,
8272
+ operation: this.operation,
8273
+ inputValues: nonEmptyInputs[0].input,
8274
+ inputValidity: nonEmptyInputs[0].mask,
8275
+ inputLength: nonEmptyInputs[0].input.length,
8276
+ valuesPerRow,
8277
+ firstLevel: true,
8278
+ needsValidity
8279
+ });
8280
+ nodes.push(...reductionResult.nodes);
8281
+ } else {
8282
+ const partialValues = createTransientView(
8283
+ graph,
8284
+ `${this.id}-chunk-values`,
8285
+ this.input.format,
8286
+ nonEmptyInputs.length * valuesPerRow
8287
+ );
8288
+ const partialValidity = needsValidity ? createTransientView(graph, `${this.id}-chunk-validity`, "uint32", nonEmptyInputs.length) : void 0;
8289
+ nonEmptyInputs.forEach(({ input, mask }, partialIndex) => {
8290
+ nodes.push(
8291
+ ...addReductionLevels(graph, {
8292
+ id: `${this.id}-chunk-${partialIndex}`,
8293
+ format: this.input.format,
8294
+ operation: this.operation,
8295
+ inputValues: input,
8296
+ inputValidity: mask,
8297
+ inputLength: input.length,
8298
+ valuesPerRow,
8299
+ firstLevel: true,
8300
+ needsValidity,
8301
+ finalValues: createPackedSubview(
8302
+ graph,
8303
+ partialValues,
8304
+ partialIndex * valuesPerRow,
8305
+ valuesPerRow
8306
+ ),
8307
+ finalValidity: partialValidity ? createPackedSubview(graph, partialValidity, partialIndex, 1) : void 0
8308
+ }).nodes
8309
+ );
8310
+ });
8311
+ reductionResult = addReductionLevels(graph, {
8312
+ id: `${this.id}-merge`,
8313
+ format: this.input.format,
8314
+ operation: this.operation,
8315
+ inputValues: partialValues,
8316
+ inputValidity: partialValidity,
8317
+ inputLength: nonEmptyInputs.length,
8318
+ valuesPerRow,
8319
+ firstLevel: false,
8320
+ needsValidity
8321
+ });
8322
+ nodes.push(...reductionResult.nodes);
8323
+ }
8324
+ nodes.push(
8325
+ ...addFinalizeReductionPass(graph, {
8326
+ id: `${this.id}-finalize`,
8327
+ format: this.input.format,
8328
+ inputValues: reductionResult.values,
8329
+ inputValidity: reductionResult.validity,
8330
+ output: this.output,
8331
+ valuesPerRow
8332
+ })
8333
+ );
8334
+ return nodes;
7400
8335
  }
7401
- if (length === input.length) return input;
7402
- const chunks = input instanceof GraphVectorView ? input.data : [input];
7403
- let remaining = length;
7404
- const data = [];
7405
- for (const chunk of chunks) {
7406
- const chunkLength = Math.min(remaining, chunk.length);
7407
- data.push(
7408
- chunkLength === chunk.length ? chunk : graph.createDataView(chunk.buffer, {
7409
- format: chunk.format,
7410
- length: chunkLength,
7411
- byteOffset: chunk.byteOffset,
7412
- byteStride: chunk.byteStride,
7413
- rowByteLength: chunk.rowByteLength
8336
+ };
8337
+ function addReductionLevels(graph, props) {
8338
+ const nodes = [];
8339
+ let currentValues = props.inputValues;
8340
+ let currentValidity = props.inputValidity;
8341
+ let currentLength = props.inputLength;
8342
+ let levelIndex = 0;
8343
+ while (currentLength > 1 || levelIndex === 0) {
8344
+ const nextLength = Math.ceil(currentLength / REDUCTION_WORKGROUP_SIZE);
8345
+ const isLastLevel = nextLength === 1;
8346
+ const nextValues = isLastLevel && props.finalValues ? props.finalValues : createTransientView(
8347
+ graph,
8348
+ `${props.id}-level-${levelIndex}-values`,
8349
+ props.format,
8350
+ nextLength * props.valuesPerRow
8351
+ );
8352
+ const nextValidity = props.needsValidity ? isLastLevel && props.finalValidity ? props.finalValidity : createTransientView(
8353
+ graph,
8354
+ `${props.id}-level-${levelIndex}-validity`,
8355
+ "uint32",
8356
+ nextLength
8357
+ ) : void 0;
8358
+ nodes.push(
8359
+ ...addReductionLevelPass(graph, {
8360
+ id: `${props.id}-level-${levelIndex}`,
8361
+ format: props.format,
8362
+ operation: props.operation,
8363
+ inputValues: currentValues,
8364
+ inputValidity: currentValidity,
8365
+ outputValues: nextValues,
8366
+ outputValidity: nextValidity,
8367
+ inputLength: currentLength,
8368
+ valuesPerRow: props.valuesPerRow,
8369
+ firstLevel: props.firstLevel && levelIndex === 0
7414
8370
  })
7415
8371
  );
7416
- remaining -= chunkLength;
7417
- if (remaining === 0) break;
8372
+ currentValues = nextValues;
8373
+ currentValidity = nextValidity;
8374
+ currentLength = nextLength;
8375
+ levelIndex++;
7418
8376
  }
7419
- return input instanceof GraphVectorView ? new GraphVectorView({
7420
- ...input,
8377
+ return { values: currentValues, validity: currentValidity, nodes };
8378
+ }
8379
+ function createPackedSubview(graph, view, elementOffset, length) {
8380
+ return graph.createDataView(view.buffer, {
8381
+ format: view.format,
7421
8382
  length,
7422
- valueLength: length * (getGPUVectorFormatInfo(input.format).listSize ?? 1),
7423
- data
7424
- }) : data[0];
8383
+ byteOffset: view.byteOffset + elementOffset * view.rowByteLength
8384
+ });
8385
+ }
8386
+ function getReductionInputs(input) {
8387
+ return input instanceof GraphVectorView ? input.data : [input];
8388
+ }
8389
+ function getReductionMasks(mask) {
8390
+ return mask instanceof GraphVectorView ? mask.data : [mask];
7425
8391
  }
8392
+ function addReductionLevelPass(graph, props) {
8393
+ const nodes = [];
8394
+ const dispatchLayout = getBoundedDispatchLayout(
8395
+ "GPUReduction",
8396
+ props.inputLength,
8397
+ REDUCTION_WORKGROUP_SIZE,
8398
+ graph.device.limits.maxComputeWorkgroupsPerDimension
8399
+ );
8400
+ const shaderType = getShaderType(props.format);
8401
+ const zero = getZeroLiteral(props.format);
8402
+ const isSum = props.operation === "sum";
8403
+ const isExtent = props.operation === "extent";
8404
+ const validityBinding = props.inputValidity ? "@group(0) @binding(1) var<storage, read> inputValidity: array<u32>;" : "";
8405
+ const outputValuesBinding = props.inputValidity ? 2 : 1;
8406
+ const outputValidityBinding = outputValuesBinding + 1;
8407
+ const finiteExpression = props.format === "float32" ? "value == value && abs(value) <= 3.402823466e+38" : "true";
8408
+ const normalizeMaskedFloatSum = props.firstLevel && props.inputValidity && props.format === "float32" && isSum ? "\n if (valid == 0u) { value = 0.0; secondValue = 0.0; }" : "";
8409
+ const readRawValue = `value = inputValues[INPUT_OFFSET + index];
8410
+ secondValue = value;
8411
+ valid = select(0u, 1u, ${finiteExpression});${normalizeMaskedFloatSum}`;
8412
+ const readFirst = props.firstLevel ? props.inputValidity ? `if (inputValidity[VALIDITY_OFFSET + index] != 0u) {
8413
+ ${readRawValue}
8414
+ }` : readRawValue : `value = inputValues[INPUT_OFFSET + index * VALUES_PER_ROW];
8415
+ secondValue = inputValues[INPUT_OFFSET + index * VALUES_PER_ROW + ${isExtent ? "1u" : "0u"}];
8416
+ ${props.inputValidity ? "valid = inputValidity[VALIDITY_OFFSET + index];" : "valid = 1u;"}`;
8417
+ const combine = isSum ? "firstScratch[lane] = firstScratch[lane] + firstScratch[lane + stride];" : `let rightValid = validityScratch[lane + stride];
8418
+ if (rightValid != 0u) {
8419
+ if (validityScratch[lane] == 0u) {
8420
+ firstScratch[lane] = firstScratch[lane + stride];
8421
+ secondScratch[lane] = secondScratch[lane + stride];
8422
+ } else {
8423
+ firstScratch[lane] = ${props.operation === "max" ? "max" : "min"}(firstScratch[lane], firstScratch[lane + stride]);
8424
+ secondScratch[lane] = ${isExtent ? "max" : props.operation === "max" ? "max" : "min"}(secondScratch[lane], secondScratch[lane + stride]);
8425
+ }
8426
+ validityScratch[lane] = 1u;
8427
+ }`;
8428
+ const strategy = getGPUReductionStrategy(graph.device);
8429
+ const reductionSource = strategy === "subgroups" ? getSubgroupReductionSource({
8430
+ format: props.format,
8431
+ operation: props.operation,
8432
+ combine
8433
+ }) : getPortableReductionSource(combine);
8434
+ const source = (
8435
+ /* wgsl */
8436
+ `
8437
+ ${strategy === "subgroups" ? "enable subgroups;\nrequires subgroup_id;" : ""}
8438
+ const ELEMENT_COUNT: u32 = ${props.inputLength}u;
8439
+ const VALUES_PER_ROW: u32 = ${props.valuesPerRow}u;
8440
+ const INPUT_OFFSET: u32 = ${getViewElementOffset(props.inputValues)}u;
8441
+ ${props.inputValidity ? `const VALIDITY_OFFSET: u32 = ${getViewElementOffset(props.inputValidity)}u;` : ""}
8442
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(props.outputValues)}u;
8443
+ ${props.outputValidity ? `const OUTPUT_VALIDITY_OFFSET: u32 = ${getViewElementOffset(props.outputValidity)}u;` : ""}
8444
+ @group(0) @binding(0) var<storage, read> inputValues: array<${shaderType}>;
8445
+ ${validityBinding}
8446
+ @group(0) @binding(${outputValuesBinding}) var<storage, read_write> outputValues: array<${shaderType}>;
8447
+ ${props.outputValidity ? `@group(0) @binding(${outputValidityBinding}) var<storage, read_write> outputValidity: array<u32>;` : ""}
8448
+ var<workgroup> firstScratch: array<${shaderType}, ${REDUCTION_WORKGROUP_SIZE}>;
8449
+ var<workgroup> secondScratch: array<${shaderType}, ${REDUCTION_WORKGROUP_SIZE}>;
8450
+ var<workgroup> validityScratch: array<u32, ${REDUCTION_WORKGROUP_SIZE}>;
7426
8451
 
7427
- // src/gpu-core/graph-vector-view-utils.ts
7428
- function getGraphVectorData(vector) {
7429
- return vector instanceof GraphVectorView ? vector.data : [vector];
8452
+ @compute @workgroup_size(${REDUCTION_WORKGROUP_SIZE}) fn main(
8453
+ @builtin(local_invocation_index) localInvocationIndex: u32,
8454
+ ${strategy === "subgroups" ? "@builtin(subgroup_invocation_id) subgroupInvocationId: u32,\n @builtin(subgroup_size) subgroupSize: u32,\n @builtin(subgroup_id) subgroupId: u32," : ""}
8455
+ @builtin(workgroup_id) workgroupId: vec3<u32>
8456
+ ) {
8457
+ ${getBoundedInvocationIndexSource(dispatchLayout, REDUCTION_WORKGROUP_SIZE)}
8458
+ if (workgroupIndex >= ${Math.ceil(props.inputLength / REDUCTION_WORKGROUP_SIZE)}u) {
8459
+ return;
7430
8460
  }
7431
- function alignGraphVectorViews(graph, vectors) {
7432
- const length = vectors[0]?.length ?? 0;
7433
- if (vectors.some((vector) => vector.length !== length)) {
7434
- throw new Error("Aligned vectors must have equal logical lengths");
8461
+ let lane = localInvocationIndex;
8462
+ var value = ${zero};
8463
+ var secondValue = ${zero};
8464
+ var valid = 0u;
8465
+ if (index < ELEMENT_COUNT) {
8466
+ ${readFirst}
8467
+ }
8468
+ ${reductionSource}
8469
+ if (lane == 0u) {
8470
+ outputValues[OUTPUT_OFFSET + workgroupIndex * VALUES_PER_ROW] = firstScratch[0];
8471
+ ${isExtent ? "outputValues[OUTPUT_OFFSET + workgroupIndex * VALUES_PER_ROW + 1u] = secondScratch[0];" : ""}
8472
+ ${props.outputValidity ? "outputValidity[OUTPUT_VALIDITY_OFFSET + workgroupIndex] = validityScratch[0];" : ""}
8473
+ }
8474
+ }`
8475
+ );
8476
+ const resources = [
8477
+ { buffer: props.inputValues, usage: "storage-read" },
8478
+ ...props.inputValidity ? [{ buffer: props.inputValidity, usage: "storage-read" }] : [],
8479
+ { buffer: props.outputValues, usage: "storage-write" },
8480
+ ...props.outputValidity ? [{ buffer: props.outputValidity, usage: "storage-write" }] : []
8481
+ ];
8482
+ const bindings = { inputValues: props.inputValues };
8483
+ if (props.inputValidity) bindings["inputValidity"] = props.inputValidity;
8484
+ bindings["outputValues"] = props.outputValues;
8485
+ if (props.outputValidity) bindings["outputValidity"] = props.outputValidity;
8486
+ nodes.push(
8487
+ ...addKernelPass2(graph, {
8488
+ id: props.id,
8489
+ source,
8490
+ resources,
8491
+ bindings,
8492
+ dispatchLayout
8493
+ })
8494
+ );
8495
+ return nodes;
8496
+ }
8497
+ function getPortableReductionSource(combine) {
8498
+ return `firstScratch[lane] = value;
8499
+ secondScratch[lane] = secondValue;
8500
+ validityScratch[lane] = valid;
8501
+ workgroupBarrier();
8502
+ var stride = ${REDUCTION_WORKGROUP_SIZE / 2}u;
8503
+ loop {
8504
+ if (lane < stride) {
8505
+ ${combine}
7435
8506
  }
7436
- const chunks = vectors.map(getGraphVectorData);
7437
- const indices = vectors.map(() => 0);
7438
- const offsets = vectors.map(() => 0);
7439
- const result = [];
7440
- let position = 0;
7441
- while (position < length) {
7442
- for (let index = 0; index < chunks.length; index++) {
7443
- while (chunks[index][indices[index]]?.length === offsets[index]) {
7444
- indices[index]++;
7445
- offsets[index] = 0;
7446
- }
7447
- }
7448
- const current = chunks.map((data, index) => data[indices[index]]);
7449
- const span = Math.min(...current.map((data, index) => data.length - offsets[index]));
7450
- const aligned = [];
7451
- for (let index = 0; index < current.length; index++) {
7452
- const data = current[index];
7453
- const matchingIndex = current.findIndex(
7454
- (candidate, candidateIndex) => candidateIndex < index && candidate === data && offsets[candidateIndex] === offsets[index]
7455
- );
7456
- aligned.push(
7457
- matchingIndex >= 0 ? aligned[matchingIndex] : offsets[index] === 0 && span === data.length ? data : graph.createDataView(data.buffer, {
7458
- format: data.format,
7459
- length: span,
7460
- byteOffset: data.byteOffset + offsets[index] * data.byteStride,
7461
- byteStride: data.byteStride,
7462
- rowByteLength: data.rowByteLength
7463
- })
7464
- );
8507
+ workgroupBarrier();
8508
+ if (stride == 1u) { break; }
8509
+ stride = stride / 2u;
8510
+ }`;
8511
+ }
8512
+ function getSubgroupReductionSource(props) {
8513
+ const firstCollective = getSubgroupCollective(
8514
+ props.format,
8515
+ props.operation === "extent" ? "min" : props.operation,
8516
+ "value",
8517
+ "valid"
8518
+ );
8519
+ const secondCollective = getSubgroupCollective(
8520
+ props.format,
8521
+ props.operation === "extent" ? "max" : props.operation,
8522
+ "secondValue",
8523
+ "valid"
8524
+ );
8525
+ return `let subgroupValid = subgroupMax(valid);
8526
+ let subgroupFirst = ${firstCollective};
8527
+ let subgroupSecond = ${secondCollective};
8528
+ if (subgroupInvocationId == 0u) {
8529
+ firstScratch[subgroupId] = subgroupFirst;
8530
+ secondScratch[subgroupId] = subgroupSecond;
8531
+ validityScratch[subgroupId] = subgroupValid;
8532
+ }
8533
+ workgroupBarrier();
8534
+ let subgroupCount = ${REDUCTION_WORKGROUP_SIZE}u / subgroupSize;
8535
+ if (subgroupCount > 1u) {
8536
+ var stride = subgroupCount / 2u;
8537
+ loop {
8538
+ if (lane < stride) {
8539
+ ${props.combine}
7465
8540
  }
7466
- result.push(aligned);
7467
- for (let index = 0; index < offsets.length; index++) offsets[index] += span;
7468
- position += span;
8541
+ workgroupBarrier();
8542
+ if (stride == 1u) { break; }
8543
+ stride = stride / 2u;
7469
8544
  }
7470
- return result;
8545
+ }`;
7471
8546
  }
7472
-
7473
- // src/gpu-core/gpu-subgroup-utils.ts
7474
- function getGPUShaderSubgroupStrategy(device, options = {}) {
7475
- const supportsSubgroups = device.features?.has("subgroups");
7476
- const supportsRequiredLanguageFeatures = !options.requiresSubgroupId || device.wgslLanguageFeatures?.has("subgroup_id");
7477
- return supportsSubgroups && supportsRequiredLanguageFeatures ? "subgroups" : "portable";
8547
+ function getSubgroupCollective(format, operation, value, validity) {
8548
+ if (operation === "sum") {
8549
+ return `subgroupAdd(${value})`;
8550
+ }
8551
+ const identity = getReductionIdentity(format, operation);
8552
+ const collective = operation === "min" ? "subgroupMin" : "subgroupMax";
8553
+ return `${collective}(select(${identity}, ${value}, ${validity} != 0u))`;
8554
+ }
8555
+ function getReductionIdentity(format, operation) {
8556
+ if (format === "uint32") {
8557
+ return operation === "min" ? "4294967295u" : "0u";
8558
+ }
8559
+ if (format === "sint32") {
8560
+ return operation === "min" ? "2147483647" : "(-2147483647 - 1)";
8561
+ }
8562
+ return operation === "min" ? "3.402823466e+38" : "-3.402823466e+38";
8563
+ }
8564
+ function addFinalizeReductionPass(graph, props) {
8565
+ const nodes = [];
8566
+ const shaderType = getShaderType(props.format);
8567
+ const zero = getZeroLiteral(props.format);
8568
+ const outputLines = Array.from({ length: props.valuesPerRow }, (_, index) => {
8569
+ const value = `inputValues[INPUT_OFFSET + ${index}u]`;
8570
+ return `outputValues[OUTPUT_OFFSET + ${index}u] = ${props.inputValidity ? `select(${zero}, ${value}, valid)` : value};`;
8571
+ }).join("\n ");
8572
+ const source = (
8573
+ /* wgsl */
8574
+ `
8575
+ const INPUT_OFFSET: u32 = ${getViewElementOffset(props.inputValues)}u;
8576
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(props.output)}u;
8577
+ ${props.inputValidity ? `const VALIDITY_OFFSET: u32 = ${getViewElementOffset(props.inputValidity)}u;` : ""}
8578
+ @group(0) @binding(0) var<storage, read> inputValues: array<${shaderType}>;
8579
+ ${props.inputValidity ? "@group(0) @binding(1) var<storage, read> inputValidity: array<u32>;" : ""}
8580
+ @group(0) @binding(${props.inputValidity ? 2 : 1}) var<storage, read_write> outputValues: array<${shaderType}>;
8581
+ @compute @workgroup_size(1) fn main() {
8582
+ ${props.inputValidity ? "let valid = inputValidity[VALIDITY_OFFSET] != 0u;" : ""}
8583
+ ${outputLines}
8584
+ }`
8585
+ );
8586
+ nodes.push(
8587
+ ...addKernelPass2(graph, {
8588
+ id: props.id,
8589
+ source,
8590
+ resources: [
8591
+ { buffer: props.inputValues, usage: "storage-read" },
8592
+ ...props.inputValidity ? [{ buffer: props.inputValidity, usage: "storage-read" }] : [],
8593
+ { buffer: props.output, usage: "storage-write" }
8594
+ ],
8595
+ bindings: {
8596
+ inputValues: props.inputValues,
8597
+ ...props.inputValidity ? { inputValidity: props.inputValidity } : {},
8598
+ outputValues: props.output
8599
+ },
8600
+ dispatchCount: 1
8601
+ })
8602
+ );
8603
+ return nodes;
8604
+ }
8605
+ function addClearReductionPass(graph, id, output) {
8606
+ const nodes = [];
8607
+ const passId = `${id}-clear`;
8608
+ const shaderType = getShaderType(output.format);
8609
+ const zero = getZeroLiteral(output.format);
8610
+ nodes.push(
8611
+ ...addKernelPass2(graph, {
8612
+ id: passId,
8613
+ source: `const OUTPUT_OFFSET: u32 = ${getViewElementOffset(output)}u;
8614
+ @group(0) @binding(0) var<storage, read_write> outputValues: array<${shaderType}>;
8615
+ @compute @workgroup_size(1) fn main() {
8616
+ for (var index = 0u; index < ${output.length}u; index++) { outputValues[OUTPUT_OFFSET + index] = ${zero}; }
8617
+ }`,
8618
+ resources: [{ buffer: output, usage: "storage-write" }],
8619
+ bindings: { outputValues: output },
8620
+ dispatchCount: 1
8621
+ })
8622
+ );
8623
+ return nodes;
8624
+ }
8625
+ function addKernelPass2(graph, props) {
8626
+ const { x, y, z } = props.dispatchLayout ?? { x: props.dispatchCount ?? 1, y: 1, z: 1 };
8627
+ const node = createGPUComputeCommandNode({
8628
+ id: props.id,
8629
+ resources: props.resources,
8630
+ compile: ({ device }) => {
8631
+ const bindingNames = Object.keys(props.bindings);
8632
+ const kernel = new Kernel(device, {
8633
+ id: props.id,
8634
+ source: props.source,
8635
+ shaderLayout: {
8636
+ bindings: bindingNames.map((name, location) => ({
8637
+ name,
8638
+ type: "storage",
8639
+ group: 0,
8640
+ location
8641
+ }))
8642
+ }
8643
+ });
8644
+ return {
8645
+ encode: ({ computePass, getBuffer }) => {
8646
+ const bindings = {};
8647
+ for (const [name, view] of Object.entries(props.bindings)) {
8648
+ bindings[name] = getViewBinding(view, getBuffer);
8649
+ }
8650
+ kernel.dispatch(computePass, { bindings, x, y, z });
8651
+ },
8652
+ destroy: () => kernel.destroy()
8653
+ };
8654
+ }
8655
+ });
8656
+ return [setGPUComputeDispatchWorkgroups(node, [x, y, z])];
8657
+ }
8658
+ function getShaderType(format) {
8659
+ return format === "uint32" ? "u32" : format === "sint32" ? "i32" : "f32";
8660
+ }
8661
+ function getZeroLiteral(format) {
8662
+ return format === "uint32" ? "0u" : format === "sint32" ? "0" : "0.0";
7478
8663
  }
7479
8664
 
7480
8665
  // src/gpu-core/gpu-scan.ts
@@ -7641,8 +8826,8 @@ var __exports__ = (() => {
7641
8826
  mode: props.mode,
7642
8827
  segmentFlags: chunk.segmentFlags,
7643
8828
  outputSegmentPrefixes: chunkSegmentPrefixes?.[partialIndex],
7644
- finalSum: createPackedSubview(graph, chunkTotals, partialIndex),
7645
- finalSegmentFlag: chunkSegmentFlags ? createPackedSubview(graph, chunkSegmentFlags, partialIndex) : void 0,
8829
+ finalSum: createPackedSubview2(graph, chunkTotals, partialIndex),
8830
+ finalSegmentFlag: chunkSegmentFlags ? createPackedSubview2(graph, chunkSegmentFlags, partialIndex) : void 0,
7646
8831
  maxComputeWorkgroupsPerDimension
7647
8832
  })
7648
8833
  );
@@ -7771,7 +8956,7 @@ var __exports__ = (() => {
7771
8956
  }
7772
8957
  return nodes;
7773
8958
  }
7774
- function createPackedSubview(graph, view, index) {
8959
+ function createPackedSubview2(graph, view, index) {
7775
8960
  return graph.createDataView(view.buffer, {
7776
8961
  format: "uint32",
7777
8962
  length: 1,
@@ -9485,7 +10670,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
9485
10670
 
9486
10671
  // src/gpu-core/gpu-gather.ts
9487
10672
  var GATHER_WORKGROUP_SIZE = 256;
9488
- var UINT32_BYTE_LENGTH3 = Uint32Array.BYTES_PER_ELEMENT;
10673
+ var UINT32_BYTE_LENGTH4 = Uint32Array.BYTES_PER_ELEMENT;
9489
10674
  var GPUGather = class {
9490
10675
  id;
9491
10676
  source;
@@ -9517,7 +10702,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
9517
10702
  if (getGraphVectorData(this.output).some((chunk) => inputBuffers.has(chunk.buffer))) {
9518
10703
  throw new Error(`${this.id} output must use a separate buffer`);
9519
10704
  }
9520
- this.wordsPerRow = getGPUVectorFormatInfo(this.source.format).byteLength / UINT32_BYTE_LENGTH3;
10705
+ this.wordsPerRow = getGPUVectorFormatInfo(this.source.format).byteLength / UINT32_BYTE_LENGTH4;
9521
10706
  }
9522
10707
  getCommandNodes(graph) {
9523
10708
  return getGatherCommandNodes(graph, this);
@@ -9573,7 +10758,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
9573
10758
  commandCount: 1,
9574
10759
  maximumWorkgroupCount: dispatchLayout.x * dispatchLayout.y * dispatchLayout.z,
9575
10760
  maximumInvocationCount: dispatchLayout.x * dispatchLayout.y * dispatchLayout.z * GATHER_WORKGROUP_SIZE,
9576
- readByteLength: sourceView ? indices.length * (UINT32_BYTE_LENGTH3 + sourceView.rowByteLength) : 0,
10761
+ readByteLength: sourceView ? indices.length * (UINT32_BYTE_LENGTH4 + sourceView.rowByteLength) : 0,
9577
10762
  writeByteLength: indices.length * destination.rowByteLength
9578
10763
  },
9579
10764
  resources: [
@@ -9639,7 +10824,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
9639
10824
  throw new Error(`${name} must use a fixed-width GPU data format`);
9640
10825
  }
9641
10826
  const formatInfo = getGPUVectorFormatInfo(view.format);
9642
- if ((packed ? view.byteStride !== formatInfo.byteLength : view.byteStride < formatInfo.byteLength || view.byteStride % UINT32_BYTE_LENGTH3 !== 0) || view.rowByteLength !== formatInfo.byteLength || view.byteOffset % UINT32_BYTE_LENGTH3 !== 0 || view.rowByteLength % UINT32_BYTE_LENGTH3 !== 0) {
10827
+ if ((packed ? view.byteStride !== formatInfo.byteLength : view.byteStride < formatInfo.byteLength || view.byteStride % UINT32_BYTE_LENGTH4 !== 0) || view.rowByteLength !== formatInfo.byteLength || view.byteOffset % UINT32_BYTE_LENGTH4 !== 0 || view.rowByteLength % UINT32_BYTE_LENGTH4 !== 0) {
9643
10828
  throw new Error(`${name} must be packed, uint32-aligned GPU data with 32-bit-word rows`);
9644
10829
  }
9645
10830
  }
@@ -9668,7 +10853,7 @@ fn main(
9668
10853
  ${source ? `
9669
10854
  let sourceIndex = indices[INDEX_OFFSET + index];
9670
10855
  if (sourceIndex >= SOURCE_ROW_OFFSET && sourceIndex - SOURCE_ROW_OFFSET < SOURCE_LENGTH) {
9671
- let sourceBase = SOURCE_OFFSET + (sourceIndex - SOURCE_ROW_OFFSET) * ${source.byteStride / UINT32_BYTE_LENGTH3}u;
10856
+ let sourceBase = SOURCE_OFFSET + (sourceIndex - SOURCE_ROW_OFFSET) * ${source.byteStride / UINT32_BYTE_LENGTH4}u;
9672
10857
  for (var word = 0u; word < WORDS_PER_ROW; word++) {
9673
10858
  outputWords[outputBase + word] = sourceWords[sourceBase + word];
9674
10859
  }
@@ -10386,6 +11571,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
10386
11571
  capabilities;
10387
11572
  lowerings;
10388
11573
  compactionIndex = 0;
11574
+ aggregationIndex = 0;
10389
11575
  constructor(device, lowerings = []) {
10390
11576
  this.device = device;
10391
11577
  this.capabilities = Object.freeze({
@@ -10409,6 +11595,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
10409
11595
  }
10410
11596
  compile(program, bindings = {}) {
10411
11597
  this.compactionIndex = 0;
11598
+ this.aggregationIndex = 0;
10412
11599
  program = program.clone();
10413
11600
  for (const vector of program.vectors) {
10414
11601
  const binding = bindings.vectors?.[vector.id];
@@ -10586,6 +11773,54 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
10586
11773
  return [
10587
11774
  { type: "vector-upload", lower: lowerGPUUpload },
10588
11775
  { type: "vector-copy", lower: lowerGPUCopy },
11776
+ {
11777
+ type: "group-aggregation",
11778
+ lower: (operation, context) => {
11779
+ const { props } = operation;
11780
+ const id = `${operation.id}-${this.aggregationIndex++}`;
11781
+ const keys = context.resolveVector(props.keys);
11782
+ const mask = props.mask ? context.resolveVector(props.mask) : void 0;
11783
+ if (props.operation === "count") {
11784
+ context.graph.add(
11785
+ new GPUGroupAggregation({
11786
+ id,
11787
+ keys,
11788
+ mask,
11789
+ operation: "count",
11790
+ output: getAggregationOutput(context.resolveVector(props.output))
11791
+ })
11792
+ );
11793
+ } else {
11794
+ context.graph.add(
11795
+ new GPUGroupAggregation({
11796
+ id,
11797
+ keys,
11798
+ mask,
11799
+ operation: props.operation,
11800
+ values: context.resolveVector(props.values),
11801
+ output: getAggregationOutput(context.resolveVector(props.output))
11802
+ })
11803
+ );
11804
+ }
11805
+ }
11806
+ },
11807
+ {
11808
+ type: "reduction",
11809
+ lower: (operation, context) => {
11810
+ const { props } = operation;
11811
+ context.graph.add(
11812
+ new GPUReduction({
11813
+ id: `${operation.id}-${this.aggregationIndex++}`,
11814
+ input: context.resolveVector(props.input),
11815
+ mask: props.mask ? context.resolveVector(props.mask) : void 0,
11816
+ operation: props.operation,
11817
+ output: getAggregationOutput(
11818
+ context.resolveVector(props.output)
11819
+ )
11820
+ })
11821
+ );
11822
+ }
11823
+ },
10589
11824
  {
10590
11825
  type: "compaction",
10591
11826
  lower: (operation, context) => {
@@ -10945,6 +12180,10 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
10945
12180
  }
10946
12181
  return lengths;
10947
12182
  }
12183
+ function getAggregationOutput(output) {
12184
+ (0, import_core18.assert)(output.data.length === 1);
12185
+ return output.data[0];
12186
+ }
10948
12187
 
10949
12188
  // src/gpu-core/gpu-expression-plan.ts
10950
12189
  var import_core20 = __toESM(require_core(), 1);
@@ -11018,7 +12257,17 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
11018
12257
  }
11019
12258
  };
11020
12259
 
11021
- // ../../node_modules/@math.gl/core/dist/expressions/vendor/jsep/runtime.js
12260
+ // ../../node_modules/@math.gl/expressions/dist/diagnostic-log.js
12261
+ function reportDiagnosticError(log3, error) {
12262
+ if (log3) {
12263
+ try {
12264
+ log3.error(error instanceof Error ? error.message : String(error), error)();
12265
+ } catch {
12266
+ }
12267
+ }
12268
+ }
12269
+
12270
+ // ../../node_modules/@math.gl/expressions/dist/expressions/vendor/jsep/runtime.js
11022
12271
  var Hooks = class {
11023
12272
  /**
11024
12273
  * @callback HookCallback
@@ -11963,10 +13212,15 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
11963
13212
  jsep.plugins.register(ternary);
11964
13213
  var runtime_default = jsep;
11965
13214
 
11966
- // ../../node_modules/@math.gl/core/dist/expressions/expression-eval.js
13215
+ // ../../node_modules/@math.gl/expressions/dist/expressions/expression-eval.js
11967
13216
  var jsep2 = runtime_default;
11968
- function parse(expression) {
11969
- return typeof expression === "string" ? jsep2(expression) : expression;
13217
+ function parse(expression, options) {
13218
+ try {
13219
+ return typeof expression === "string" ? jsep2(expression) : expression;
13220
+ } catch (error) {
13221
+ reportDiagnosticError(options?.log, error);
13222
+ throw error;
13223
+ }
11970
13224
  }
11971
13225
 
11972
13226
  // src/gpu-core/gpu-expression-operation.ts
@@ -14084,6 +15338,95 @@ ${operation.fragmentSource}
14084
15338
  return trees.reduce((count, tree) => count + 1 + countOperations(tree.children ?? []), 0);
14085
15339
  }
14086
15340
 
15341
+ // src/gpu-core/gpu-semantic-aggregation-operation.ts
15342
+ var import_core26 = __toESM(require_core(), 1);
15343
+ var GPUGraphGroupAggregation = class {
15344
+ /** Semantic operation discriminator. */
15345
+ type = "group-aggregation";
15346
+ /** Stable operation identifier. */
15347
+ id;
15348
+ /** Immutable logical operation arguments. */
15349
+ props;
15350
+ /** Describe grouped reduction without allocating or reading GPU storage. */
15351
+ constructor(props) {
15352
+ (0, import_core26.assert)(
15353
+ props.groupCount === void 0 || Number.isSafeInteger(props.groupCount) && props.groupCount > 0
15354
+ );
15355
+ this.id = props.id ?? `${getGPUOperationValueName(props.output)}-group-aggregation`;
15356
+ this.props = Object.freeze({ ...props });
15357
+ }
15358
+ /** Logical dependencies and optional inferred output shape. */
15359
+ get contract() {
15360
+ const { keys, mask, output, groupCount } = this.props;
15361
+ const values = this.props.operation === "count" ? void 0 : this.props.values;
15362
+ return {
15363
+ outputs: ({ getValue }) => {
15364
+ for (const input of [keys, mask]) {
15365
+ if (input) {
15366
+ const descriptor = getValue(getGPUOperationValueName(input));
15367
+ (0, import_core26.assert)(descriptor.type === "vector" && descriptor.format === "uint32");
15368
+ }
15369
+ }
15370
+ if (values) {
15371
+ const descriptor = getValue(getGPUOperationValueName(values));
15372
+ (0, import_core26.assert)(descriptor.type === "vector" && descriptor.format === "float32");
15373
+ }
15374
+ return {
15375
+ [getGPUOperationValueName(output)]: gpuGraph.vector(
15376
+ this.props.operation === "count" ? "uint32" : "float32",
15377
+ { length: groupCount }
15378
+ )
15379
+ };
15380
+ },
15381
+ values: [
15382
+ { value: keys, access: "read" },
15383
+ ...values ? [{ value: values, access: "read" }] : [],
15384
+ ...mask ? [{ value: mask, access: "read" }] : [],
15385
+ { value: output, access: "write" }
15386
+ ]
15387
+ };
15388
+ }
15389
+ };
15390
+ var GPUGraphReduction = class {
15391
+ /** Semantic operation discriminator. */
15392
+ type = "reduction";
15393
+ /** Stable operation identifier. */
15394
+ id;
15395
+ /** Immutable logical operation arguments. */
15396
+ props;
15397
+ /** Describe a scalar reduction without allocating or reading GPU storage. */
15398
+ constructor(props) {
15399
+ this.id = props.id ?? `${getGPUOperationValueName(props.output)}-reduction`;
15400
+ this.props = Object.freeze({ ...props });
15401
+ }
15402
+ /** Infer a packed one-row result, or two rows for extent. */
15403
+ get contract() {
15404
+ const { input, mask, output, operation } = this.props;
15405
+ return {
15406
+ outputs: ({ getValue }) => {
15407
+ const descriptor = getValue(getGPUOperationValueName(input));
15408
+ (0, import_core26.assert)(descriptor.type === "vector");
15409
+ const { format } = descriptor;
15410
+ (0, import_core26.assert)(format === "uint32" || format === "sint32" || format === "float32");
15411
+ if (mask) {
15412
+ const selection = getValue(getGPUOperationValueName(mask));
15413
+ (0, import_core26.assert)(selection.type === "vector" && selection.format === "uint32");
15414
+ }
15415
+ return {
15416
+ [getGPUOperationValueName(output)]: gpuGraph.vector(format, {
15417
+ length: operation === "extent" ? 2 : 1
15418
+ })
15419
+ };
15420
+ },
15421
+ values: [
15422
+ { value: input, access: "read" },
15423
+ ...mask ? [{ value: mask, access: "read" }] : [],
15424
+ { value: output, access: "write" }
15425
+ ]
15426
+ };
15427
+ }
15428
+ };
15429
+
14087
15430
  // src/gpu-core/gpu-command-graph-autotuner.ts
14088
15431
  var PROFILE_VERSION = 1;
14089
15432
  var GPUCommandGraphAutotuner = class {
@@ -14781,7 +16124,7 @@ ${operation.fragmentSource}
14781
16124
  }
14782
16125
 
14783
16126
  // src/gpu-core/gpu-compaction-operation.ts
14784
- var import_core26 = __toESM(require_core(), 1);
16127
+ var import_core27 = __toESM(require_core(), 1);
14785
16128
  var GPUCompactionOperation = class {
14786
16129
  type = "compaction";
14787
16130
  id;
@@ -14796,9 +16139,9 @@ ${operation.fragmentSource}
14796
16139
  outputs: ({ getValue }) => {
14797
16140
  for (const name of [input, flags]) {
14798
16141
  const value = getValue(name);
14799
- (0, import_core26.assert)(value.type === "vector" && value.format === "uint32");
16142
+ (0, import_core27.assert)(value.type === "vector" && value.format === "uint32");
14800
16143
  }
14801
- (0, import_core26.assert)(output !== count);
16144
+ (0, import_core27.assert)(output !== count);
14802
16145
  return { [output]: gpuGraph.vector("uint32"), [count]: gpuGraph.scalar("uint32") };
14803
16146
  },
14804
16147
  values: [