@graphty/webgpu-graph-algorithms 0.0.0 → 0.2.0

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 (269) hide show
  1. package/README.md +344 -23
  2. package/dist/browser.d.ts +1 -0
  3. package/dist/browser.js +32 -0
  4. package/dist/browser.js.map +1 -0
  5. package/dist/chunks/context-E6iKaeuJ.js +3136 -0
  6. package/dist/chunks/context-E6iKaeuJ.js.map +1 -0
  7. package/dist/node.d.ts +1 -0
  8. package/dist/node.js +131 -0
  9. package/dist/node.js.map +1 -0
  10. package/dist/src/accelerator.d.ts +26 -0
  11. package/dist/src/accelerator.d.ts.map +1 -0
  12. package/dist/src/accelerator.js +101 -0
  13. package/dist/src/accelerator.js.map +1 -0
  14. package/dist/src/algorithms/degree.d.ts +35 -0
  15. package/dist/src/algorithms/degree.d.ts.map +1 -0
  16. package/dist/src/algorithms/degree.js +119 -0
  17. package/dist/src/algorithms/degree.js.map +1 -0
  18. package/dist/src/browser/index.d.ts +23 -0
  19. package/dist/src/browser/index.d.ts.map +1 -0
  20. package/dist/src/browser/index.js +48 -0
  21. package/dist/src/browser/index.js.map +1 -0
  22. package/dist/src/constants.d.ts +92 -0
  23. package/dist/src/constants.d.ts.map +1 -0
  24. package/dist/src/constants.js +92 -0
  25. package/dist/src/constants.js.map +1 -0
  26. package/dist/src/context.d.ts +84 -0
  27. package/dist/src/context.d.ts.map +1 -0
  28. package/dist/src/context.js +304 -0
  29. package/dist/src/context.js.map +1 -0
  30. package/dist/src/device/acquire.d.ts +57 -0
  31. package/dist/src/device/acquire.d.ts.map +1 -0
  32. package/dist/src/device/acquire.js +232 -0
  33. package/dist/src/device/acquire.js.map +1 -0
  34. package/dist/src/device/caps.d.ts +43 -0
  35. package/dist/src/device/caps.d.ts.map +1 -0
  36. package/dist/src/device/caps.js +104 -0
  37. package/dist/src/device/caps.js.map +1 -0
  38. package/dist/src/device/error-scope.d.ts +75 -0
  39. package/dist/src/device/error-scope.d.ts.map +1 -0
  40. package/dist/src/device/error-scope.js +152 -0
  41. package/dist/src/device/error-scope.js.map +1 -0
  42. package/dist/src/device/lost.d.ts +51 -0
  43. package/dist/src/device/lost.d.ts.map +1 -0
  44. package/dist/src/device/lost.js +130 -0
  45. package/dist/src/device/lost.js.map +1 -0
  46. package/dist/src/device/webgpu-constants.d.ts +31 -0
  47. package/dist/src/device/webgpu-constants.d.ts.map +1 -0
  48. package/dist/src/device/webgpu-constants.js +31 -0
  49. package/dist/src/device/webgpu-constants.js.map +1 -0
  50. package/dist/src/errors.d.ts +56 -0
  51. package/dist/src/errors.d.ts.map +1 -0
  52. package/dist/src/errors.js +57 -0
  53. package/dist/src/errors.js.map +1 -0
  54. package/dist/src/index.d.ts +29 -0
  55. package/dist/src/index.d.ts.map +1 -0
  56. package/dist/src/index.js +27 -0
  57. package/dist/src/index.js.map +1 -0
  58. package/dist/src/kernel/batch.d.ts +116 -0
  59. package/dist/src/kernel/batch.d.ts.map +1 -0
  60. package/dist/src/kernel/batch.js +335 -0
  61. package/dist/src/kernel/batch.js.map +1 -0
  62. package/dist/src/kernel/dispatch.d.ts +59 -0
  63. package/dist/src/kernel/dispatch.d.ts.map +1 -0
  64. package/dist/src/kernel/dispatch.js +139 -0
  65. package/dist/src/kernel/dispatch.js.map +1 -0
  66. package/dist/src/kernel/kernel.d.ts +84 -0
  67. package/dist/src/kernel/kernel.d.ts.map +1 -0
  68. package/dist/src/kernel/kernel.js +239 -0
  69. package/dist/src/kernel/kernel.js.map +1 -0
  70. package/dist/src/kernel/pipeline-cache.d.ts +90 -0
  71. package/dist/src/kernel/pipeline-cache.d.ts.map +1 -0
  72. package/dist/src/kernel/pipeline-cache.js +251 -0
  73. package/dist/src/kernel/pipeline-cache.js.map +1 -0
  74. package/dist/src/kernel/prelude.d.ts +35 -0
  75. package/dist/src/kernel/prelude.d.ts.map +1 -0
  76. package/dist/src/kernel/prelude.js +211 -0
  77. package/dist/src/kernel/prelude.js.map +1 -0
  78. package/dist/src/kernel/profiler.d.ts +64 -0
  79. package/dist/src/kernel/profiler.d.ts.map +1 -0
  80. package/dist/src/kernel/profiler.js +120 -0
  81. package/dist/src/kernel/profiler.js.map +1 -0
  82. package/dist/src/kernel/struct-block.d.ts +122 -0
  83. package/dist/src/kernel/struct-block.d.ts.map +1 -0
  84. package/dist/src/kernel/struct-block.js +353 -0
  85. package/dist/src/kernel/struct-block.js.map +1 -0
  86. package/dist/src/kernel/uniform-ring.d.ts +70 -0
  87. package/dist/src/kernel/uniform-ring.d.ts.map +1 -0
  88. package/dist/src/kernel/uniform-ring.js +146 -0
  89. package/dist/src/kernel/uniform-ring.js.map +1 -0
  90. package/dist/src/kernel/wgsl.d.ts +88 -0
  91. package/dist/src/kernel/wgsl.d.ts.map +1 -0
  92. package/dist/src/kernel/wgsl.js +390 -0
  93. package/dist/src/kernel/wgsl.js.map +1 -0
  94. package/dist/src/kernels.d.ts +81 -0
  95. package/dist/src/kernels.d.ts.map +1 -0
  96. package/dist/src/kernels.js +417 -0
  97. package/dist/src/kernels.js.map +1 -0
  98. package/dist/src/layouts/force-simulation.d.ts +498 -0
  99. package/dist/src/layouts/force-simulation.d.ts.map +1 -0
  100. package/dist/src/layouts/force-simulation.js +1650 -0
  101. package/dist/src/layouts/force-simulation.js.map +1 -0
  102. package/dist/src/layouts/forceatlas2.d.ts +210 -0
  103. package/dist/src/layouts/forceatlas2.d.ts.map +1 -0
  104. package/dist/src/layouts/forceatlas2.js +759 -0
  105. package/dist/src/layouts/forceatlas2.js.map +1 -0
  106. package/dist/src/layouts/inputs.d.ts +40 -0
  107. package/dist/src/layouts/inputs.d.ts.map +1 -0
  108. package/dist/src/layouts/inputs.js +185 -0
  109. package/dist/src/layouts/inputs.js.map +1 -0
  110. package/dist/src/layouts/repulsion-exact.d.ts +85 -0
  111. package/dist/src/layouts/repulsion-exact.d.ts.map +1 -0
  112. package/dist/src/layouts/repulsion-exact.js +134 -0
  113. package/dist/src/layouts/repulsion-exact.js.map +1 -0
  114. package/dist/src/layouts/seed.d.ts +56 -0
  115. package/dist/src/layouts/seed.d.ts.map +1 -0
  116. package/dist/src/layouts/seed.js +173 -0
  117. package/dist/src/layouts/seed.js.map +1 -0
  118. package/dist/src/memory/buffer-pool.d.ts +73 -0
  119. package/dist/src/memory/buffer-pool.d.ts.map +1 -0
  120. package/dist/src/memory/buffer-pool.js +170 -0
  121. package/dist/src/memory/buffer-pool.js.map +1 -0
  122. package/dist/src/memory/lease.d.ts +53 -0
  123. package/dist/src/memory/lease.d.ts.map +1 -0
  124. package/dist/src/memory/lease.js +85 -0
  125. package/dist/src/memory/lease.js.map +1 -0
  126. package/dist/src/memory/readback.d.ts +143 -0
  127. package/dist/src/memory/readback.d.ts.map +1 -0
  128. package/dist/src/memory/readback.js +375 -0
  129. package/dist/src/memory/readback.js.map +1 -0
  130. package/dist/src/memory/residency.d.ts +83 -0
  131. package/dist/src/memory/residency.d.ts.map +1 -0
  132. package/dist/src/memory/residency.js +573 -0
  133. package/dist/src/memory/residency.js.map +1 -0
  134. package/dist/src/memory/upload-plan.d.ts +101 -0
  135. package/dist/src/memory/upload-plan.d.ts.map +1 -0
  136. package/dist/src/memory/upload-plan.js +265 -0
  137. package/dist/src/memory/upload-plan.js.map +1 -0
  138. package/dist/src/node/index.d.ts +64 -0
  139. package/dist/src/node/index.d.ts.map +1 -0
  140. package/dist/src/node/index.js +183 -0
  141. package/dist/src/node/index.js.map +1 -0
  142. package/dist/src/primitives/reduce.d.ts +57 -0
  143. package/dist/src/primitives/reduce.d.ts.map +1 -0
  144. package/dist/src/primitives/reduce.js +161 -0
  145. package/dist/src/primitives/reduce.js.map +1 -0
  146. package/dist/src/primitives/segmented-reduce.d.ts +38 -0
  147. package/dist/src/primitives/segmented-reduce.d.ts.map +1 -0
  148. package/dist/src/primitives/segmented-reduce.js +211 -0
  149. package/dist/src/primitives/segmented-reduce.js.map +1 -0
  150. package/dist/src/types/accelerator.d.ts +209 -0
  151. package/dist/src/types/accelerator.d.ts.map +1 -0
  152. package/dist/src/types/accelerator.js +8 -0
  153. package/dist/src/types/accelerator.js.map +1 -0
  154. package/dist/src/types/context.d.ts +114 -0
  155. package/dist/src/types/context.d.ts.map +1 -0
  156. package/dist/src/types/context.js +7 -0
  157. package/dist/src/types/context.js.map +1 -0
  158. package/dist/src/types/layout.d.ts +95 -0
  159. package/dist/src/types/layout.d.ts.map +1 -0
  160. package/dist/src/types/layout.js +6 -0
  161. package/dist/src/types/layout.js.map +1 -0
  162. package/dist/src/types/memory.d.ts +22 -0
  163. package/dist/src/types/memory.d.ts.map +1 -0
  164. package/dist/src/types/memory.js +7 -0
  165. package/dist/src/types/memory.js.map +1 -0
  166. package/dist/src/types/options.d.ts +78 -0
  167. package/dist/src/types/options.d.ts.map +1 -0
  168. package/dist/src/types/options.js +7 -0
  169. package/dist/src/types/options.js.map +1 -0
  170. package/dist/src/types/run.d.ts +13 -0
  171. package/dist/src/types/run.d.ts.map +1 -0
  172. package/dist/src/types/run.js +6 -0
  173. package/dist/src/types/run.js.map +1 -0
  174. package/dist/src/wgsl/degree.wgsl.d.ts +10 -0
  175. package/dist/src/wgsl/degree.wgsl.d.ts.map +1 -0
  176. package/dist/src/wgsl/degree.wgsl.js +25 -0
  177. package/dist/src/wgsl/degree.wgsl.js.map +1 -0
  178. package/dist/src/wgsl/fa2-attraction.wgsl.d.ts +12 -0
  179. package/dist/src/wgsl/fa2-attraction.wgsl.d.ts.map +1 -0
  180. package/dist/src/wgsl/fa2-attraction.wgsl.js +37 -0
  181. package/dist/src/wgsl/fa2-attraction.wgsl.js.map +1 -0
  182. package/dist/src/wgsl/fa2-integrate.wgsl.d.ts +13 -0
  183. package/dist/src/wgsl/fa2-integrate.wgsl.d.ts.map +1 -0
  184. package/dist/src/wgsl/fa2-integrate.wgsl.js +69 -0
  185. package/dist/src/wgsl/fa2-integrate.wgsl.js.map +1 -0
  186. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.d.ts +12 -0
  187. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.d.ts.map +1 -0
  188. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.js +79 -0
  189. package/dist/src/wgsl/fa2-repulsion-exact.wgsl.js.map +1 -0
  190. package/dist/src/wgsl/fa2-speed-finalize.wgsl.d.ts +15 -0
  191. package/dist/src/wgsl/fa2-speed-finalize.wgsl.d.ts.map +1 -0
  192. package/dist/src/wgsl/fa2-speed-finalize.wgsl.js +54 -0
  193. package/dist/src/wgsl/fa2-speed-finalize.wgsl.js.map +1 -0
  194. package/dist/src/wgsl/fa2-stats-finalize.wgsl.d.ts +14 -0
  195. package/dist/src/wgsl/fa2-stats-finalize.wgsl.d.ts.map +1 -0
  196. package/dist/src/wgsl/fa2-stats-finalize.wgsl.js +57 -0
  197. package/dist/src/wgsl/fa2-stats-finalize.wgsl.js.map +1 -0
  198. package/dist/src/wgsl/fa2-to-scene.wgsl.d.ts +11 -0
  199. package/dist/src/wgsl/fa2-to-scene.wgsl.d.ts.map +1 -0
  200. package/dist/src/wgsl/fa2-to-scene.wgsl.js +19 -0
  201. package/dist/src/wgsl/fa2-to-scene.wgsl.js.map +1 -0
  202. package/dist/src/wgsl/fill.wgsl.d.ts +7 -0
  203. package/dist/src/wgsl/fill.wgsl.d.ts.map +1 -0
  204. package/dist/src/wgsl/fill.wgsl.js +14 -0
  205. package/dist/src/wgsl/fill.wgsl.js.map +1 -0
  206. package/dist/src/wgsl/reduce.wgsl.d.ts +10 -0
  207. package/dist/src/wgsl/reduce.wgsl.d.ts.map +1 -0
  208. package/dist/src/wgsl/reduce.wgsl.js +63 -0
  209. package/dist/src/wgsl/reduce.wgsl.js.map +1 -0
  210. package/dist/src/wgsl/segmented-reduce.wgsl.d.ts +13 -0
  211. package/dist/src/wgsl/segmented-reduce.wgsl.d.ts.map +1 -0
  212. package/dist/src/wgsl/segmented-reduce.wgsl.js +35 -0
  213. package/dist/src/wgsl/segmented-reduce.wgsl.js.map +1 -0
  214. package/dist/tsconfig.build.tsbuildinfo +1 -0
  215. package/dist/webgpu-graph-algorithms.d.ts +1 -0
  216. package/dist/webgpu-graph-algorithms.js +4454 -0
  217. package/dist/webgpu-graph-algorithms.js.map +1 -0
  218. package/package.json +108 -17
  219. package/src/accelerator.ts +117 -0
  220. package/src/algorithms/degree.ts +142 -0
  221. package/src/browser/index.ts +57 -0
  222. package/src/constants.ts +116 -0
  223. package/src/context.ts +399 -0
  224. package/src/device/acquire.ts +256 -0
  225. package/src/device/caps.ts +122 -0
  226. package/src/device/error-scope.ts +171 -0
  227. package/src/device/lost.ts +142 -0
  228. package/src/device/webgpu-constants.ts +44 -0
  229. package/src/errors.ts +94 -0
  230. package/src/index.ts +102 -0
  231. package/src/kernel/batch.ts +427 -0
  232. package/src/kernel/dispatch.ts +162 -0
  233. package/src/kernel/kernel.ts +311 -0
  234. package/src/kernel/pipeline-cache.ts +288 -0
  235. package/src/kernel/prelude.ts +229 -0
  236. package/src/kernel/profiler.ts +148 -0
  237. package/src/kernel/struct-block.ts +439 -0
  238. package/src/kernel/uniform-ring.ts +184 -0
  239. package/src/kernel/wgsl.ts +490 -0
  240. package/src/kernels.ts +511 -0
  241. package/src/layouts/force-simulation.ts +2111 -0
  242. package/src/layouts/forceatlas2.ts +942 -0
  243. package/src/layouts/inputs.ts +252 -0
  244. package/src/layouts/repulsion-exact.ts +183 -0
  245. package/src/layouts/seed.ts +198 -0
  246. package/src/memory/buffer-pool.ts +204 -0
  247. package/src/memory/lease.ts +93 -0
  248. package/src/memory/readback.ts +429 -0
  249. package/src/memory/residency.ts +753 -0
  250. package/src/memory/upload-plan.ts +350 -0
  251. package/src/node/index.ts +230 -0
  252. package/src/primitives/reduce.ts +233 -0
  253. package/src/primitives/segmented-reduce.ts +270 -0
  254. package/src/types/accelerator.ts +236 -0
  255. package/src/types/context.ts +135 -0
  256. package/src/types/layout.ts +103 -0
  257. package/src/types/memory.ts +23 -0
  258. package/src/types/options.ts +84 -0
  259. package/src/types/run.ts +13 -0
  260. package/src/wgsl/degree.wgsl.ts +24 -0
  261. package/src/wgsl/fa2-attraction.wgsl.ts +37 -0
  262. package/src/wgsl/fa2-integrate.wgsl.ts +69 -0
  263. package/src/wgsl/fa2-repulsion-exact.wgsl.ts +78 -0
  264. package/src/wgsl/fa2-speed-finalize.wgsl.ts +53 -0
  265. package/src/wgsl/fa2-stats-finalize.wgsl.ts +57 -0
  266. package/src/wgsl/fa2-to-scene.wgsl.ts +19 -0
  267. package/src/wgsl/fill.wgsl.ts +13 -0
  268. package/src/wgsl/reduce.wgsl.ts +62 -0
  269. package/src/wgsl/segmented-reduce.wgsl.ts +35 -0
@@ -0,0 +1,759 @@
1
+ /**
2
+ * ForceAtlas2 on the exact repulsion tier (spec 7.1-7.18; contract 3.13): the ForceModel that ForceSimulation
3
+ * drives -- the K1 K2 K3 K4 K5 sequence per iteration and toScene per batch (spec 7.4), the override set of the option
4
+ * record (spec 7.2 with the 4.6 NetworkX corrections), the per-iteration Fa2Params values, the controller resets of
5
+ * spec 7.17 and the stats decoder -- plus the two option resolvers and `createForceAtlas2`. Positions are vec4f
6
+ * (xyz + mass) in layout units on the device (D23, 7.18); the speed controller runs on the device (D15); no
7
+ * displacement clamp (D25); K2 runs the thread-per-row tier over [0, n) with USE_PERM false (P3, spec 7.5).
8
+ *
9
+ * Model decisions this file fixes (the plan of P3-T2 lists the reasons): recordIteration with no `upTo` records every
10
+ * stage including toScene; the K1-K5 dispatches of every iteration of one batch share ONE compute pass (opened by the
11
+ * batch's first recordIteration and remembered by batch id) and toScene runs in a second pass that ends it (contract
12
+ * 4.4); the fill kernel takes its FillParams from a model-owned 256-byte uniform buffer ("fillParams"); the first
13
+ * iteration after every load() zeroes oldForce with a fill (paper mode); `repulsion: "grid"` is E_UNSUPPORTED at
14
+ * load() for any n and `"auto"` above exactMaxNodes.
15
+ */
16
+ import { FA2_DEFAULTS, LAYOUT_TUNING_DEFAULTS, MAX_ITERATIONS_PER_STEP, TRACE_RECORD_BYTES, UNIFORM_SLOT_BYTES, } from "../constants.js";
17
+ import { BufferUsage } from "../device/webgpu-constants.js";
18
+ import { WebGpuGraphError } from "../errors.js";
19
+ import { plan1d } from "../kernel/dispatch.js";
20
+ import { FA2_PARAMS, FA2_STATE, FA2_TRACE, FILL_PARAMS, graphBindings, kernelSpec } from "../kernels.js";
21
+ import { ForceSimulation, } from "./force-simulation.js";
22
+ import { resolveNodeMass, resolveWeights } from "./inputs.js";
23
+ import { RepulsionExact } from "./repulsion-exact.js";
24
+ /** The stage names of one iteration in dispatch order plus the per-batch toScene (spec 7.4; contract 3.13). */
25
+ const FA2_STAGES = ["K1", "K2", "K3", "K4", "K5", "toScene"];
26
+ /** Bytes of the stride-3 f32 force arrays per node. */
27
+ const FORCE_BYTES_PER_NODE = 12;
28
+ /** The name of the model-owned FillParams buffer (a BufferSpec, reached through ModelResources.buffer). */
29
+ const FILL_PARAMS_BUFFER = "fillParams";
30
+ /** The one-workgroup dispatch of K1 (spec 7.4). */
31
+ const ONE_WORKGROUP = { x: 1, y: 1, z: 1, items: 1, stride: null };
32
+ /** Every override K2 accepts, with its default (contract 3.10.1 plus the two standard graph overrides). */
33
+ const K2_DEFAULTS = { LINLOG: false, DISTRIBUTED: false, TIER: 0, USE_PERM: false, HAS_WEIGHTS: false };
34
+ /** Every override K5 accepts, with its default. */
35
+ const K5_DEFAULTS = { SWING_MODE: 0 };
36
+ /** 2^32, the modulus of the u32 seed word (computed with `%`, never a bitwise operator). */
37
+ const U32_MODULUS = 4294967296;
38
+ /** The resolved record with no option given: FA2_DEFAULTS plus the null / origin defaults of spec 7.14. */
39
+ const DEFAULT_RESOLVED = Object.freeze({
40
+ ...FA2_DEFAULTS,
41
+ nodeMass: null,
42
+ nodeSize: null,
43
+ weight: null,
44
+ center: [0, 0, 0],
45
+ seed: null,
46
+ });
47
+ /**
48
+ * A short, safe rendering of an argument value for error messages (never String() on an object).
49
+ * @param value - the value
50
+ * @returns the rendering
51
+ */
52
+ function describeValue(value) {
53
+ if (value === null) {
54
+ return "null";
55
+ }
56
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "string") {
57
+ return String(value);
58
+ }
59
+ if (typeof value === "undefined") {
60
+ return "undefined";
61
+ }
62
+ if (typeof value === "object" && "length" in value && typeof value.length === "number") {
63
+ return `[${value.length} values]`;
64
+ }
65
+ return typeof value;
66
+ }
67
+ /**
68
+ * The E_INVALID_ARGUMENT error of an option check (contract 3.1: { argument, value, expected }).
69
+ * @param argument - the option name
70
+ * @param value - the value given
71
+ * @param expected - what was expected
72
+ * @returns the error (not thrown here)
73
+ */
74
+ function invalid(argument, value, expected) {
75
+ return new WebGpuGraphError("E_INVALID_ARGUMENT", `${argument} must be ${expected}; got ${describeValue(value)}`, {
76
+ argument,
77
+ value,
78
+ expected,
79
+ });
80
+ }
81
+ /**
82
+ * A numeric option: the given value when defined, else the fallback; validated by `check` (the value is checked as
83
+ * `unknown` so a JS caller's string or object is E_INVALID_ARGUMENT too).
84
+ * @param name - the option name
85
+ * @param given - the value given (undefined = absent)
86
+ * @param fallback - the previous record's value or the default
87
+ * @param check - the range predicate over a finite number
88
+ * @param expected - the range in words (the error message)
89
+ * @returns the value
90
+ */
91
+ function pickNumber(name, given, fallback, check, expected) {
92
+ const value = given === undefined ? fallback : given;
93
+ if (typeof value !== "number" || !Number.isFinite(value) || !check(value)) {
94
+ throw invalid(name, value, expected);
95
+ }
96
+ return value;
97
+ }
98
+ /**
99
+ * A boolean option: the given value when defined, else the fallback; a non-boolean is E_INVALID_ARGUMENT.
100
+ * @param name - the option name
101
+ * @param given - the value given (undefined = absent)
102
+ * @param fallback - the previous record's value or the default
103
+ * @returns the value
104
+ */
105
+ function pickBoolean(name, given, fallback) {
106
+ const value = given === undefined ? fallback : given;
107
+ if (typeof value !== "boolean") {
108
+ throw invalid(name, value, "a boolean");
109
+ }
110
+ return value;
111
+ }
112
+ /**
113
+ * The layout dimension: 2 or 3.
114
+ * @param given - the value given (undefined = absent)
115
+ * @param fallback - the previous record's value or the default
116
+ * @returns 2 or 3
117
+ */
118
+ function pickDim(given, fallback) {
119
+ const value = given === undefined ? fallback : given;
120
+ if (value !== 2 && value !== 3) {
121
+ throw invalid("dim", value, "2 or 3");
122
+ }
123
+ return value;
124
+ }
125
+ /**
126
+ * The scene-unit center: an array-like of 2 (z = 0) or 3 finite numbers.
127
+ * @param given - the value given (undefined = absent)
128
+ * @param fallback - the previous record's value or the default
129
+ * @returns the three components
130
+ */
131
+ function pickCenter(given, fallback) {
132
+ if (given === undefined) {
133
+ return fallback;
134
+ }
135
+ const expected = "an array of 2 or 3 finite numbers";
136
+ const value = given;
137
+ if (typeof value !== "object" || value === null || !("length" in value)) {
138
+ throw invalid("center", given, expected);
139
+ }
140
+ const { length } = value;
141
+ if (length !== 2 && length !== 3) {
142
+ throw invalid("center", given, expected);
143
+ }
144
+ const x = given[0];
145
+ const y = given[1];
146
+ const z = length === 3 ? given[2] : 0;
147
+ if (typeof x !== "number" ||
148
+ typeof y !== "number" ||
149
+ typeof z !== "number" ||
150
+ !Number.isFinite(x) ||
151
+ !Number.isFinite(y) ||
152
+ !Number.isFinite(z)) {
153
+ throw invalid("center", given, expected);
154
+ }
155
+ return [x, y, z];
156
+ }
157
+ /**
158
+ * The seed: a finite number, or null (unseeded; 0 keeps the port's "0 = unseeded" quirk through the Lcg).
159
+ * @param given - the value given (undefined = absent)
160
+ * @param fallback - the previous record's value or the default
161
+ * @returns the seed or null
162
+ */
163
+ function pickSeed(given, fallback) {
164
+ if (given === undefined) {
165
+ return fallback;
166
+ }
167
+ const value = given;
168
+ if (value !== null && (typeof value !== "number" || !Number.isFinite(value))) {
169
+ throw invalid("seed", given, "a finite number or null");
170
+ }
171
+ return value;
172
+ }
173
+ /**
174
+ * Integer >= 1.
175
+ * @param value - a finite number
176
+ * @returns whether it is a positive integer
177
+ */
178
+ function isPositiveInteger(value) {
179
+ return Number.isInteger(value) && value >= 1;
180
+ }
181
+ /**
182
+ * The u32 word written into Fa2Params.seed: 0 for null, else floor(|seed|) mod 2^32.
183
+ * @param seed - the resolved seed
184
+ * @returns the u32 value
185
+ */
186
+ function seedWord(seed) {
187
+ if (seed === null) {
188
+ return 0;
189
+ }
190
+ return Math.floor(Math.abs(seed)) % U32_MODULUS;
191
+ }
192
+ /**
193
+ * A scalar field of a block's read() result.
194
+ * @param values - the values read
195
+ * @param name - the field name
196
+ * @returns the number
197
+ */
198
+ function scalar(values, name) {
199
+ const value = values[name];
200
+ if (typeof value !== "number") {
201
+ throw invalid(name, value, "a scalar field");
202
+ }
203
+ return value;
204
+ }
205
+ /**
206
+ * A vector field of a block's read() result.
207
+ * @param values - the values read
208
+ * @param name - the field name
209
+ * @returns the components
210
+ */
211
+ function vector(values, name) {
212
+ const value = values[name];
213
+ if (typeof value === "number") {
214
+ throw invalid(name, value, "a vector field");
215
+ }
216
+ return value;
217
+ }
218
+ /**
219
+ * The override record a kernel gets: its defaults overlaid with the values present in the merged set (contract 3.9:
220
+ * a name a spec does not declare is rejected at compose time, so nothing else is passed through).
221
+ * @param merged - the merged override set of the model (plus USE_PERM / HAS_WEIGHTS from the simulation)
222
+ * @param defaults - the kernel's accepted names with their defaults
223
+ * @returns the kernel's override record, every accepted name explicit
224
+ */
225
+ function subset(merged, defaults) {
226
+ const out = {};
227
+ for (const name of Object.keys(defaults)) {
228
+ out[name] = name in merged ? merged[name] : defaults[name];
229
+ }
230
+ return out;
231
+ }
232
+ /**
233
+ * The K3 / K4 override values of a merged set (typed for RepulsionExact).
234
+ * @param merged - the merged override set
235
+ * @returns the three K3 / K4 overrides
236
+ */
237
+ function repulsionOverrides(merged) {
238
+ return {
239
+ SWING_MODE: merged.SWING_MODE === 1 ? 1 : 0,
240
+ STRONG_GRAVITY: merged.STRONG_GRAVITY === true,
241
+ GRAVITY_CENTER: merged.GRAVITY_CENTER === 1 ? 1 : 0,
242
+ };
243
+ }
244
+ // ============================================================ the resolvers
245
+ /**
246
+ * Applies FA2_DEFAULTS to the option record; validates ranges (spec 7.14; contract 3.13). With `previous` the record
247
+ * is a PATCH over it (an absent or explicitly undefined field keeps the previous value) and `maxInFlight` may not
248
+ * change (the uniform ring is sized by it at construction). `nodeSize` is E_UNSUPPORTED { option: "nodeSize" } (the
249
+ * adjustSizes correction is deferred); `dissuadeHubs` is kept and ignored, exactly like the CPU.
250
+ * @param options - the caller's options (or a setParams patch)
251
+ * @param previous - the current resolved record when resolving a patch
252
+ * @returns the frozen resolved record
253
+ */
254
+ export function resolveForceAtlas2Options(options, previous) {
255
+ const o = options ?? {};
256
+ const base = previous ?? DEFAULT_RESOLVED;
257
+ if (previous !== undefined && o.maxInFlight !== undefined && o.maxInFlight !== previous.maxInFlight) {
258
+ throw new WebGpuGraphError("E_INVALID_ARGUMENT", `maxInFlight cannot change after creation (the uniform ring is sized by it): got ${describeValue(o.maxInFlight)}, current ${previous.maxInFlight}`, { argument: "maxInFlight", value: o.maxInFlight, expected: previous.maxInFlight });
259
+ }
260
+ const nodeSize = o.nodeSize === undefined ? base.nodeSize : o.nodeSize;
261
+ if (nodeSize !== null) {
262
+ throw new WebGpuGraphError("E_UNSUPPORTED", "nodeSize (the adjustSizes correction) is not supported by the GPU ForceAtlas2 yet (spec 7.14)", { option: "nodeSize", hint: "pass nodeSize: null; the size-aware repulsion is deferred (spec 7.2, Q-25)" });
263
+ }
264
+ const resolved = {
265
+ maxIter: pickNumber("maxIter", o.maxIter, base.maxIter, isPositiveInteger, "an integer >= 1"),
266
+ jitterTolerance: pickNumber("jitterTolerance", o.jitterTolerance, base.jitterTolerance, (v) => v > 0, "> 0"),
267
+ scalingRatio: pickNumber("scalingRatio", o.scalingRatio, base.scalingRatio, (v) => v > 0, "> 0"),
268
+ gravity: pickNumber("gravity", o.gravity, base.gravity, (v) => v >= 0, ">= 0"),
269
+ strongGravity: pickBoolean("strongGravity", o.strongGravity, base.strongGravity),
270
+ distributedAction: pickBoolean("distributedAction", o.distributedAction, base.distributedAction),
271
+ linlog: pickBoolean("linlog", o.linlog, base.linlog),
272
+ nodeMass: o.nodeMass === undefined ? base.nodeMass : o.nodeMass,
273
+ nodeSize,
274
+ weight: o.weight === undefined ? base.weight : o.weight,
275
+ dissuadeHubs: pickBoolean("dissuadeHubs", o.dissuadeHubs, base.dissuadeHubs),
276
+ dim: pickDim(o.dim, base.dim),
277
+ scale: pickNumber("scale", o.scale, base.scale, (v) => v > 0, "> 0"),
278
+ center: pickCenter(o.center, base.center),
279
+ seed: pickSeed(o.seed, base.seed),
280
+ settleThreshold: pickNumber("settleThreshold", o.settleThreshold, base.settleThreshold, (v) => v >= 0, ">= 0"),
281
+ settleWindow: pickNumber("settleWindow", o.settleWindow, base.settleWindow, isPositiveInteger, "an integer >= 1"),
282
+ iterationsPerStep: pickNumber("iterationsPerStep", o.iterationsPerStep, base.iterationsPerStep, (v) => isPositiveInteger(v) && v <= MAX_ITERATIONS_PER_STEP, `an integer in [1, ${MAX_ITERATIONS_PER_STEP}]`),
283
+ maxInFlight: pickNumber("maxInFlight", o.maxInFlight, base.maxInFlight, isPositiveInteger, "an integer >= 1"),
284
+ };
285
+ return Object.freeze(resolved);
286
+ }
287
+ /**
288
+ * Applies LAYOUT_TUNING_DEFAULTS (spec 7.14); the grid knobs are validated and stored but only `repulsion`,
289
+ * `exactMaxNodes`, `deterministic` and `compat` have an effect in P3 (contract 3.3).
290
+ * @param tuning - the GPU-only knobs given (any object carrying them, e.g. the createForceAtlas2 options)
291
+ * @returns the frozen resolved tuning
292
+ */
293
+ export function resolveLayoutTuning(tuning) {
294
+ const t = tuning ?? {};
295
+ const repulsion = t.repulsion ?? LAYOUT_TUNING_DEFAULTS.repulsion;
296
+ if (repulsion !== "exact" && repulsion !== "grid" && repulsion !== "auto") {
297
+ throw invalid("repulsion", repulsion, '"exact", "grid" or "auto"');
298
+ }
299
+ const compat = t.compat ?? LAYOUT_TUNING_DEFAULTS.compat;
300
+ if (compat !== "paper" && compat !== "networkx") {
301
+ throw invalid("compat", compat, '"paper" or "networkx"');
302
+ }
303
+ const resolved = {
304
+ repulsion,
305
+ exactMaxNodes: pickNumber("exactMaxNodes", t.exactMaxNodes, LAYOUT_TUNING_DEFAULTS.exactMaxNodes, isPositiveInteger, "an integer >= 1"),
306
+ nearMax: pickNumber("nearMax", t.nearMax, LAYOUT_TUNING_DEFAULTS.nearMax, isPositiveInteger, "an integer >= 1"),
307
+ deterministic: pickBoolean("deterministic", t.deterministic, LAYOUT_TUNING_DEFAULTS.deterministic),
308
+ gridMax2D: pickNumber("gridMax2D", t.gridMax2D, LAYOUT_TUNING_DEFAULTS.gridMax2D, isPositiveInteger, "an integer >= 1"),
309
+ gridMax3D: pickNumber("gridMax3D", t.gridMax3D, LAYOUT_TUNING_DEFAULTS.gridMax3D, isPositiveInteger, "an integer >= 1"),
310
+ extentFactor: pickNumber("extentFactor", t.extentFactor, LAYOUT_TUNING_DEFAULTS.extentFactor, (v) => v > 0, "> 0"),
311
+ compat,
312
+ };
313
+ return Object.freeze(resolved);
314
+ }
315
+ /** The ForceAtlas2 model (spec 7.4: K1 K2 K3 K4 K5 per iteration; toScene once per batch). Stages: ["K1", "K2", "K3", "K4", "K5", "toScene"]. */
316
+ export class ForceAtlas2Model {
317
+ /**
318
+ * Creates the model for one simulation.
319
+ * @param tuning - the resolved GPU-only tuning (compat selects SWING_MODE / GRAVITY_CENTER; repulsion and
320
+ * exactMaxNodes the tier rule)
321
+ * @param resolved - the resolved option record at creation
322
+ */
323
+ constructor(tuning, resolved) {
324
+ /** The model kind of spec 7.19. */
325
+ this.kind = "forceatlas2";
326
+ /** The stage names in dispatch order (the `upTo` vocabulary of recordIteration and debugRunStages). */
327
+ this.stages = FA2_STAGES;
328
+ /** Fa2Params: the per-iteration uniform block (the simulation writes the shared fields into it). */
329
+ this.params = FA2_PARAMS;
330
+ /** Fa2State: the state header block (the simulation allocates and initialises it through this layout). */
331
+ this.state = FA2_STATE;
332
+ /** Fa2Trace: one record per iteration of a batch. */
333
+ this.trace = FA2_TRACE;
334
+ /** The resources of the last bind(), or null before the first. */
335
+ this.resources = null;
336
+ /** The kernels and bind groups of the last bind(), or null before it (and for n === 0). */
337
+ this.bound = null;
338
+ /** Armed by onLoad(): the next recordIteration zeroes oldForce first (paper mode). */
339
+ this.resetOldForce = false;
340
+ /**
341
+ * The K1-K5 compute pass of the batch being recorded, keyed by CommandBatch.id (unique per batch): every
342
+ * recordIteration of one batch dispatches into it (ONE pass per batch, contract 4.4); null between batches and
343
+ * after the toScene pass ended it (PLAN DECISION 2).
344
+ */
345
+ this.openPass = null;
346
+ this.tuning = tuning;
347
+ this.current = resolved;
348
+ }
349
+ /**
350
+ * The SWING_MODE of this model: 1 in networkx mode (accumulated, position-mixed sums; m|F| local swing), else 0.
351
+ * @returns 0 or 1
352
+ */
353
+ get swingMode() {
354
+ return this.tuning.compat === "networkx" ? 1 : 0;
355
+ }
356
+ /**
357
+ * force 12n and oldForce 12n (zeroed) in BOTH swing modes (3.10.1: a writable slot is never aliased; mode 1 leaves
358
+ * oldForce unread and unwritten), plus the 256-byte FillParams uniform buffer the fill dispatches read. n = 0
359
+ * reports one node's worth of bytes so no zero-length buffer is ever created (spec 3.6).
360
+ * @param n - the node count
361
+ * @param _dim - the layout dimension (the force arrays are stride 3 in both)
362
+ * @returns the three model-owned buffer specs
363
+ */
364
+ buffers(n, _dim) {
365
+ const bytes = Math.max(1, n) * FORCE_BYTES_PER_NODE;
366
+ const usage = BufferUsage.STORAGE | BufferUsage.COPY_SRC | BufferUsage.COPY_DST;
367
+ return [
368
+ { name: "force", byteLength: bytes, usage, zero: true },
369
+ { name: "oldForce", byteLength: bytes, usage, zero: true },
370
+ {
371
+ name: FILL_PARAMS_BUFFER,
372
+ byteLength: UNIFORM_SLOT_BYTES,
373
+ usage: BufferUsage.UNIFORM | BufferUsage.COPY_DST,
374
+ zero: false,
375
+ },
376
+ ];
377
+ }
378
+ /**
379
+ * { mass: resolveNodeMass(s, resolved.nodeMass), weights: resolveWeights(s, resolved.weight) } (3.13 inputs.ts),
380
+ * after the tier rule of spec 7.8 / lead f: `repulsion: "grid"` is E_UNSUPPORTED { feature: "repulsion.grid" }
381
+ * for any n and `"auto"` when n > exactMaxNodes (the grid tier lands in P4); `"exact"` always runs.
382
+ * @param s - the snapshot being loaded
383
+ * @param options - the simulation's current option record
384
+ * @returns the per-load inputs
385
+ */
386
+ inputs(s, options) {
387
+ const resolved = resolveForceAtlas2Options(options, this.current);
388
+ const { repulsion, exactMaxNodes } = this.tuning;
389
+ const n = s.nodeCount;
390
+ if (repulsion === "grid" || (repulsion === "auto" && n > exactMaxNodes)) {
391
+ throw new WebGpuGraphError("E_UNSUPPORTED", repulsion === "grid"
392
+ ? 'repulsion: "grid" is not available yet (the grid tier lands in P4)'
393
+ : `the graph has ${n} nodes, above exactMaxNodes ${exactMaxNodes}, and the grid tier lands in P4`, {
394
+ feature: "repulsion.grid",
395
+ hint: 'pass repulsion: "exact" (or raise exactMaxNodes) to run the exact tier at this size',
396
+ });
397
+ }
398
+ return { mass: resolveNodeMass(s, resolved.nodeMass), weights: resolveWeights(s, resolved.weight) };
399
+ }
400
+ /**
401
+ * { LINLOG, DISTRIBUTED, TIER: 0, SWING_MODE: compat === "networkx" ? 1 : 0, STRONG_GRAVITY, GRAVITY_CENTER:
402
+ * compat === "networkx" ? 1 : 0 }; USE_PERM / HAS_WEIGHTS are merged in by the simulation from ModelResources
403
+ * (3.10, never from core.hasWeights). A pure query: the simulation calls it with the current AND the next record
404
+ * inside setParams() to decide the recompile, so it never touches the model's record (PLAN DECISION 12).
405
+ * @param options - an option record (the simulation's current one, or the next one of a setParams patch)
406
+ * @returns the model's own override set
407
+ */
408
+ overrides(options) {
409
+ const resolved = resolveForceAtlas2Options(options, this.current);
410
+ const mode = this.swingMode;
411
+ return {
412
+ LINLOG: resolved.linlog,
413
+ DISTRIBUTED: resolved.distributedAction,
414
+ TIER: 0,
415
+ SWING_MODE: mode,
416
+ STRONG_GRAVITY: resolved.strongGravity,
417
+ GRAVITY_CENTER: mode,
418
+ };
419
+ }
420
+ /**
421
+ * The seven module specs of an override set in dispatch order -- K1, K2, K3, K4, K5, toScene, fill -- each with
422
+ * only the override names its entry declares (K2 also USE_PERM / HAS_WEIGHTS), for warm() and the compile matrix.
423
+ * @param overrides - the merged override set (the model's plus USE_PERM / HAS_WEIGHTS)
424
+ * @param _subgroups - accepted for the ForceModel interface and unused: every reducing FA2 body carries
425
+ * needs: ["subgroups"] in its registry entry and the composer picks the twin from caps.features (contract 4.3)
426
+ * @returns the specs
427
+ */
428
+ specs(overrides, _subgroups) {
429
+ const [repulsionSpec, speedSpec] = RepulsionExact.specs(repulsionOverrides(overrides));
430
+ return [
431
+ kernelSpec("fa2-stats-finalize"),
432
+ kernelSpec("fa2-attraction", subset(overrides, K2_DEFAULTS)),
433
+ repulsionSpec,
434
+ speedSpec,
435
+ kernelSpec("fa2-integrate", subset(overrides, K5_DEFAULTS)),
436
+ kernelSpec("fa2-to-scene"),
437
+ kernelSpec("fill"),
438
+ ];
439
+ }
440
+ /**
441
+ * Compiles (through the cache) and binds every kernel against the buffers of this load(): K1, K2 (or the fill of
442
+ * force when arcCount === 0), K3 + K4 through RepulsionExact, K5, toScene, and the fill of oldForce; writes the
443
+ * FillParams { count: 3n, value: 0, mode: 0 } into the model's uniform buffer. With n === 0 nothing is bound.
444
+ * @param resources - the graph, the shared and model buffers, the ring and the cache
445
+ * @param overrides - the merged override set
446
+ */
447
+ async bind(resources, overrides) {
448
+ this.dropBound();
449
+ this.resources = resources;
450
+ const { n, pipelines, caps, core, perm, ring, device } = resources;
451
+ if (n === 0) {
452
+ return;
453
+ }
454
+ const [k1, k2, k5, toScene, fill] = await Promise.all([
455
+ pipelines.kernel(kernelSpec("fa2-stats-finalize")),
456
+ pipelines.kernel(kernelSpec("fa2-attraction", subset(overrides, K2_DEFAULTS))),
457
+ pipelines.kernel(kernelSpec("fa2-integrate", subset(overrides, K5_DEFAULTS))),
458
+ pipelines.kernel(kernelSpec("fa2-to-scene")),
459
+ pipelines.kernel(kernelSpec("fill")),
460
+ ]);
461
+ const repulsion = await RepulsionExact.create(pipelines, caps, repulsionOverrides(overrides));
462
+ if (this.resources !== resources) {
463
+ // a newer bind() superseded this one while the pipelines compiled; its own bind groups stand
464
+ return;
465
+ }
466
+ const pos = resources.buffer("positions");
467
+ const scene = resources.buffer("scenePositions");
468
+ const fixed = resources.buffer("fixed");
469
+ const partials = resources.buffer("partials");
470
+ const state = resources.buffer("state");
471
+ const trace = resources.buffer("trace");
472
+ const force = resources.buffer("force");
473
+ const oldForce = resources.buffer("oldForce");
474
+ const fillParamsBuffer = resources.buffer(FILL_PARAMS_BUFFER);
475
+ const params = ring.binding(FA2_PARAMS);
476
+ const fillParams = {
477
+ buffer: fillParamsBuffer.buffer,
478
+ offset: fillParamsBuffer.offset,
479
+ size: FILL_PARAMS.byteLength,
480
+ window: null,
481
+ };
482
+ const fillBytes = new ArrayBuffer(FILL_PARAMS.byteLength);
483
+ FILL_PARAMS.write(new DataView(fillBytes), { count: 3 * n, value: 0, mode: 0 });
484
+ device.queue.writeBuffer(fillParamsBuffer.buffer, fillParamsBuffer.offset, fillBytes);
485
+ const hasArcs = core.colIdx !== null;
486
+ repulsion.bind({ pos, state, trace, force, oldForce, fixedMask: fixed, partials, params });
487
+ const wg = k1.workgroupSize;
488
+ this.bound = {
489
+ n,
490
+ plan: plan1d(n, wg, caps),
491
+ fillPlan: plan1d(3 * n, wg, caps),
492
+ k1,
493
+ k1Bound: k1.bind({ partials, S: state, T: trace, P: params }),
494
+ k2,
495
+ k2Bound: hasArcs
496
+ ? k2.bind({ ...graphBindings(core, perm, resources.weights), pos, force, P: params })
497
+ : null,
498
+ repulsion,
499
+ k5,
500
+ k5Bound: k5.bind({ force, oldForce, fixedMask: fixed, S: state, pos, partials, P: params }),
501
+ toScene,
502
+ toSceneBound: toScene.bind({ pos, scene, P: params }),
503
+ fill,
504
+ fillForceBound: hasArcs ? null : fill.bind({ dst: force, P: fillParams }),
505
+ fillOldBound: this.swingMode === 0 ? fill.bind({ dst: oldForce, P: fillParams }) : null,
506
+ };
507
+ }
508
+ /**
509
+ * The Fa2Params values of one iteration (the simulation overwrites the shared fields n, dim, flags,
510
+ * iterationIndex, seed, scale, center and settleThreshold with the same values plus the flags).
511
+ * @param iteration - the trace slot of the iteration inside its batch
512
+ * @param options - the simulation's current option record
513
+ * @returns the uniform values
514
+ */
515
+ paramsFor(iteration, options) {
516
+ const { n } = this.requireResources();
517
+ const resolved = resolveForceAtlas2Options(options, this.current);
518
+ const { nearMax, extentFactor } = this.tuning;
519
+ return {
520
+ n,
521
+ dim: resolved.dim,
522
+ flags: 0,
523
+ tierStart: 0,
524
+ tierEnd: n,
525
+ iterationIndex: iteration,
526
+ seed: seedWord(resolved.seed),
527
+ nearMax,
528
+ scalingRatio: resolved.scalingRatio,
529
+ gravity: resolved.gravity,
530
+ jitterTolerance: resolved.jitterTolerance,
531
+ scale: resolved.scale,
532
+ center: [resolved.center[0], resolved.center[1], resolved.center[2], 0],
533
+ settleThreshold: resolved.settleThreshold,
534
+ extentFactor,
535
+ gridMax: 0,
536
+ levels: 0,
537
+ pad: [0, 0, 0, 0],
538
+ };
539
+ }
540
+ /**
541
+ * Records one iteration into the batch: K1, K2 (or the fill of force when arcCount === 0), K3, K4, K5 in the
542
+ * batch's ONE K1-K5 compute pass (opened by the first call of a batch and reused by every later call with the
543
+ * same batch.id, PLAN DECISION 2), then toScene in a second pass that ends it, stopping after stage `upTo` when
544
+ * given (spec 7.4; debugRunStages / inspect, spec 11.9 item 2). The simulation passes "K5" for iterations
545
+ * 0..k-2 and undefined for the last, so toScene runs once per batch. The first call after load() zeroes
546
+ * oldForce before K1 (paper mode). With n === 0 nothing is recorded (PLAN DECISION 9); a call before bind()
547
+ * completed is E_NOT_LOADED (never a silent no-op).
548
+ * @param batch - the batch being recorded
549
+ * @param slot - the UniformRing slot holding this iteration's Fa2Params
550
+ * @param tier - "exact" (the grid tier is E_UNSUPPORTED until P4; the simulation never passes "grid")
551
+ * @param upTo - a stage name to stop after; undefined records every stage including toScene
552
+ */
553
+ recordIteration(batch, slot, tier, upTo) {
554
+ if (tier === "grid") {
555
+ throw new WebGpuGraphError("E_UNSUPPORTED", "the grid repulsion tier lands in P4", {
556
+ feature: "repulsion.grid",
557
+ hint: 'pass repulsion: "exact"',
558
+ });
559
+ }
560
+ const resources = this.requireResources();
561
+ const stop = upTo === undefined ? FA2_STAGES.length - 1 : this.stageIndex(upTo);
562
+ const { bound } = this;
563
+ if (bound === null) {
564
+ if (resources.n === 0) {
565
+ return;
566
+ }
567
+ throw new WebGpuGraphError("E_NOT_LOADED", "the ForceAtlas2 model is not bound (bind() has not completed)", {
568
+ state: "loaded",
569
+ });
570
+ }
571
+ const offset = resources.ring.offsetOf(slot);
572
+ const pass = this.openPass !== null && this.openPass.id === batch.id ? this.openPass.pass : batch.pass("fa2");
573
+ this.openPass = { id: batch.id, pass };
574
+ if (this.resetOldForce) {
575
+ this.resetOldForce = false;
576
+ if (bound.fillOldBound !== null) {
577
+ bound.fill.dispatch(pass, bound.fillOldBound, bound.fillPlan, [0]);
578
+ }
579
+ }
580
+ bound.k1.dispatch(pass, bound.k1Bound, ONE_WORKGROUP, [offset]);
581
+ if (stop < 1) {
582
+ return;
583
+ }
584
+ if (bound.k2Bound !== null) {
585
+ bound.k2.dispatch(pass, bound.k2Bound, bound.plan, [offset]);
586
+ }
587
+ else if (bound.fillForceBound !== null) {
588
+ bound.fill.dispatch(pass, bound.fillForceBound, bound.fillPlan, [0]);
589
+ }
590
+ if (stop < 2) {
591
+ return;
592
+ }
593
+ bound.repulsion.recordRepulsion(pass, bound.n, offset);
594
+ if (stop < 3) {
595
+ return;
596
+ }
597
+ bound.repulsion.recordSpeedFinalize(pass, offset);
598
+ if (stop < 4) {
599
+ return;
600
+ }
601
+ bound.k5.dispatch(pass, bound.k5Bound, bound.plan, [offset]);
602
+ if (stop < 5) {
603
+ return;
604
+ }
605
+ // the second pass ends the K1-K5 pass; the batch is complete after toScene, so nothing reuses it
606
+ this.openPass = null;
607
+ const scenePass = batch.pass("fa2-to-scene");
608
+ bound.toScene.dispatch(scenePass, bound.toSceneBound, bound.plan, [offset]);
609
+ }
610
+ /**
611
+ * speed = 1, speedEfficiency = 1, swing = 1, traction = 1 (mode 1 accumulates from 1; mode 0 overwrites them each
612
+ * iteration, the initial value is irrelevant); arms the oldForce reset of the next recordIteration.
613
+ * @param state - the state writer of the simulation
614
+ */
615
+ onLoad(state) {
616
+ state.set("speed", 1);
617
+ state.set("speedEfficiency", 1);
618
+ state.set("swing", 1);
619
+ state.set("traction", 1);
620
+ this.resetOldForce = true;
621
+ }
622
+ /**
623
+ * Mode 0: nothing (D8). Mode 1 (networkx): swing = traction = 1 (spec 7.2 "load() and reheat() reset them to 1").
624
+ * @param state - the state writer of the simulation
625
+ */
626
+ onReheat(state) {
627
+ if (this.swingMode === 1) {
628
+ state.set("swing", 1);
629
+ state.set("traction", 1);
630
+ }
631
+ }
632
+ /**
633
+ * Resets speed / speedEfficiency to 1 only when linlog, strongGravity or distributedAction changed (spec 7.17);
634
+ * a numeric tweak leaves the controller alone. The patch is validated by the same resolver the simulation uses
635
+ * and applied over the record of the constructor / the previous onSetParams -- the only place `current` moves
636
+ * (PLAN DECISION 12), so the comparison sees the record from BEFORE this setParams even though the simulation
637
+ * already queried overrides(next).
638
+ * @param patch - the setParams patch
639
+ * @param state - the state writer of the simulation
640
+ */
641
+ onSetParams(patch, state) {
642
+ const next = resolveForceAtlas2Options(patch, this.current);
643
+ const lawChanged = next.linlog !== this.current.linlog ||
644
+ next.strongGravity !== this.current.strongGravity ||
645
+ next.distributedAction !== this.current.distributedAction;
646
+ this.current = next;
647
+ if (lawChanged) {
648
+ state.set("speed", 1);
649
+ state.set("speedEfficiency", 1);
650
+ }
651
+ }
652
+ /**
653
+ * Decodes the state header and the k trace records of a completed batch (k = trace.byteLength / 32) into
654
+ * ForceAtlas2Stats: the exact tier with null grid fields; msPerIteration null (the simulation owns the clock).
655
+ * @param state - a DataView over the 256-byte state header
656
+ * @param trace - a DataView over the k Fa2Trace records of the batch
657
+ * @returns the stats
658
+ */
659
+ readStats(state, trace) {
660
+ const header = FA2_STATE.read(state);
661
+ const centroid = vector(header, "centroid");
662
+ const records = [];
663
+ const count = Math.floor(trace.byteLength / TRACE_RECORD_BYTES);
664
+ for (let i = 0; i < count; i++) {
665
+ const record = FA2_TRACE.read(trace, i * TRACE_RECORD_BYTES);
666
+ records.push({
667
+ swing: scalar(record, "swing"),
668
+ traction: scalar(record, "traction"),
669
+ speed: scalar(record, "speed"),
670
+ speedEfficiency: scalar(record, "speedEfficiency"),
671
+ meanDisplacement: scalar(record, "meanDisplacement"),
672
+ settledCount: scalar(record, "settledCount"),
673
+ });
674
+ }
675
+ return {
676
+ iteration: scalar(header, "iteration"),
677
+ meanDisplacement: scalar(header, "meanDisplacement"),
678
+ rmsRadius: scalar(header, "rmsRadius"),
679
+ layoutRadius: scalar(header, "radius"),
680
+ centroid: [centroid[0], centroid[1], centroid[2]],
681
+ repulsionTier: "exact",
682
+ maxCellOccupancy: null,
683
+ outsideGrid: null,
684
+ msPerIteration: null,
685
+ swing: scalar(header, "swing"),
686
+ traction: scalar(header, "traction"),
687
+ speed: scalar(header, "speed"),
688
+ speedEfficiency: scalar(header, "speedEfficiency"),
689
+ trace: records,
690
+ };
691
+ }
692
+ /**
693
+ * The resources of the last bind(), or E_NOT_LOADED before it.
694
+ * @returns the resources
695
+ */
696
+ requireResources() {
697
+ if (this.resources === null) {
698
+ throw new WebGpuGraphError("E_NOT_LOADED", "the ForceAtlas2 model has not been bound (load() first)", {
699
+ state: "created",
700
+ });
701
+ }
702
+ return this.resources;
703
+ }
704
+ /**
705
+ * The index of a stage name in FA2_STAGES, or E_INVALID_ARGUMENT.
706
+ * @param upTo - the stage name
707
+ * @returns its index
708
+ */
709
+ stageIndex(upTo) {
710
+ for (let i = 0; i < FA2_STAGES.length; i++) {
711
+ if (FA2_STAGES[i] === upTo) {
712
+ return i;
713
+ }
714
+ }
715
+ throw invalid("upTo", upTo, FA2_STAGES.join(" | "));
716
+ }
717
+ /**
718
+ * Drops the bind groups of the previous bind() (the buffers changed) so the cached kernels do not accumulate stale
719
+ * groups across reloads; K3 / K4 live inside RepulsionExact and keep the P1-T6 behaviour. Also forgets the pass
720
+ * of a batch recorded before the rebind.
721
+ */
722
+ dropBound() {
723
+ this.openPass = null;
724
+ const { bound } = this;
725
+ if (bound === null) {
726
+ return;
727
+ }
728
+ for (const kernel of [bound.k1, bound.k2, bound.k5, bound.toScene, bound.fill]) {
729
+ kernel.invalidate();
730
+ }
731
+ this.bound = null;
732
+ }
733
+ }
734
+ // ============================================================ the factory
735
+ /**
736
+ * The resolve callback of the simulation's setParams: the patch over the current record, re-validated (the current
737
+ * record is re-resolved first so the callback is typed without a cast).
738
+ * @param patch - the setParams patch
739
+ * @param current - the simulation's current option record
740
+ * @returns the new record
741
+ */
742
+ function resolvePatch(patch, current) {
743
+ return resolveForceAtlas2Options(patch, resolveForceAtlas2Options(current));
744
+ }
745
+ /**
746
+ * Spec 3.3 createForceAtlas2, verbatim: a GpuLayoutSimulation running ForceAtlas2 on the exact repulsion tier with
747
+ * the option defaults of spec 7.14 and the GPU-only tuning of GpuLayoutTuning (contract 3.13 "Contracts").
748
+ * @param ctx - the context (E_DISPOSED / E_DEVICE_LOST through assertReady)
749
+ * @param options - the ForceAtlas2 options and the GPU-only tuning knobs in one record
750
+ * @returns the simulation in state "created"; load() next
751
+ */
752
+ export function createForceAtlas2(ctx, options) {
753
+ ctx.assertReady();
754
+ const resolved = resolveForceAtlas2Options(options);
755
+ const tuning = resolveLayoutTuning(options);
756
+ const model = new ForceAtlas2Model(tuning, resolved);
757
+ return new ForceSimulation(ctx, model, resolved, tuning, resolvePatch);
758
+ }
759
+ //# sourceMappingURL=forceatlas2.js.map