@kineviz/gl 0.6.0 → 0.7.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.
@@ -0,0 +1,1504 @@
1
+ import*as L from"three";function re(){return typeof navigator<"u"&&!!navigator.gpu}async function he(e={}){if(!re())throw new Error("WebGPU not available: navigator.gpu is undefined. Use the WebGL backend instead.");let n=await navigator.gpu.requestAdapter({powerPreference:e.preferHighPerformance===!1?"low-power":"high-performance"});if(!n)throw new Error("WebGPU adapter request returned null (no compatible adapter found).");let t=(e.requestedFeatures??[]).filter(a=>n.features.has(a)),i=await n.requestDevice({requiredFeatures:t});return{adapter:n,device:i,features:new Set(n.features),limits:n.limits}}function Pn(e){if(e<=0)return 1;let n=Math.ceil(Math.sqrt(e));return Math.pow(2,Math.ceil(Math.log2(n)))}function Mn(e,n,r=10){if(e<=0)return r;let t;return n===3?t=Math.cbrt(e)*2:t=Math.sqrt(e)*.5,Math.max(r,t)}function me(){return{type:L.FloatType,format:L.RGBAFormat,minFilter:L.NearestFilter,magFilter:L.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1}}function _n(e){let n=me();return new L.WebGLRenderTarget(e,e,n)}function wn(e,n){let r=new L.DataTexture(e,n,n,L.RGBAFormat,L.FloatType);return r.minFilter=L.NearestFilter,r.magFilter=L.NearestFilter,r.needsUpdate=!0,r}function Cn(e){let n=[];for(let r=0;r<e;r++)for(let t=0;t<e;t++)n.push(t,r);return new Float32Array(n)}function kn(){return new L.PlaneGeometry(2,2)}function In(e=1){let i=e;return function(){return i=(1664525*i+1013904223)%4294967296,i/4294967296}}function Sn(e){return(e()-.5)*1e-6}function An(e){return()=>e}function oe(e,n,r){let t=e.length,i=10,a=Math.PI*(3-Math.sqrt(5)),s=Math.PI*20/(9+Math.sqrt(221));for(let o=0;o<t;o++){let u=e[o];if(u.index=o,u.fx!=null&&(u.x=u.fx),u.fy!=null&&(u.y=u.fy),u.fz!=null&&(u.z=u.fz),isNaN(u.x)||n>1&&isNaN(u.y)||n>2&&isNaN(u.z)){let l=i*(n>2?Math.cbrt(.5+o):n>1?Math.sqrt(.5+o):o),m=o*a,h=o*s;n===1?u.x=l:n===2?(u.x=l*Math.cos(m),u.y=l*Math.sin(m)):(u.x=l*Math.sin(m)*Math.cos(h),u.y=l*Math.cos(m),u.z=l*Math.sin(m)*Math.sin(h))}(isNaN(u.vx)||n>1&&isNaN(u.vy)||n>2&&isNaN(u.vz))&&(u.vx=0,n>1&&(u.vy=0),n>2&&(u.vz=0))}}function Fn(e,n){let r=n*n,t=new Float32Array(r*4);for(let i=0;i<e.length;i++){let a=e[i],s=i*4;t[s]=a.x||0,t[s+1]=a.y||0,t[s+2]=a.z||0,t[s+3]=i}return t}function zn(e,n){let r=n*n,t=new Float32Array(r*4);for(let i=0;i<e.length;i++){let a=e[i],s=i*4;t[s]=a.vx||0,t[s+1]=a.vy||0,t[s+2]=a.vz||0,t[s+3]=0}return t}function Tn(e,n){let r=n*n,t=new Float32Array(r*4);for(let i=0;i<e.length;i++){let a=e[i],s=i*4;t[s]=a.fx!=null||a.fy!=null||a.fz!=null?1:0,t[s+1]=0,t[s+2]=0,t[s+3]=0}return t}function Gn(e,n,r){for(let t=0;t<e.length;t++){let i=e[t],a=t*4;i.fx==null&&(i.x=n[a]),r>1&&i.fy==null&&(i.y=n[a+1]),r>2&&i.fz==null?i.z=n[a+2]:r<=2&&(i.z=0)}}var ge=`// Position integration compute shader.
2
+ //
3
+ // One invocation per node. Reads accumulated velocity, applies velocityDecay,
4
+ // CLAMPS velocity magnitude to maxVel (matches WebGL FBO path's
5
+ // \`update-position.frag.glsl\`), updates position, masks out unused dimensions,
6
+ // and writes both buffers back. Pinned nodes (pinned[i] > 0.5) keep their
7
+ // position unchanged.
8
+ //
9
+ // Why the velocity clamp matters: WebGL's update-position.frag.glsl caps
10
+ // per-tick velocity to \`spaceSize * 0.1\` (\u22481.6 units/tick for N\u2248500 in 3D).
11
+ // Without this clamp the WebGPU layout's initial frames let nodes overshoot
12
+ // the equilibrium massively \u2014 outer phyllotaxis-init nodes (radius up to 83
13
+ // for N=578) feel strong gravity and accelerate dozens of units per tick,
14
+ // blowing the layout out to thousands of units before charge can stabilize.
15
+ // Net visual: layout extent 100\xD7 wider than WebGL \u2192 nodes shrink to single
16
+ // pixels in the auto-fit camera frame.
17
+ //
18
+ // Layout \u2014 kept identical across all WebGPU force compute shaders for shared
19
+ // bind group reuse:
20
+ // group(0)
21
+ // binding(0) positions array<vec4<f32>> read_write
22
+ // binding(1) velocities array<vec4<f32>> read_write
23
+ // binding(2) pinned array<f32> read
24
+ // binding(3) params IntegrateParams uniform
25
+
26
+ struct IntegrateParams {
27
+ velocityDecay: f32,
28
+ nDim: f32,
29
+ nodeCount: f32,
30
+ maxVel: f32, // 0 = no clamp; >0 = cap per-tick |v|
31
+ }
32
+
33
+ @group(0) @binding(0) var<storage, read_write> positions: array<vec4<f32>>;
34
+ @group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
35
+ @group(0) @binding(2) var<storage, read> pinned: array<f32>;
36
+ @group(0) @binding(3) var<uniform> params: IntegrateParams;
37
+
38
+ @compute @workgroup_size(64)
39
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
40
+ let i = gid.x;
41
+ if (f32(i) >= params.nodeCount) { return; }
42
+
43
+ if (pinned[i] > 0.5) {
44
+ // Pinned nodes: zero out any accumulated velocity but keep position.
45
+ velocities[i] = vec4<f32>(0.0, 0.0, 0.0, 0.0);
46
+ return;
47
+ }
48
+
49
+ // d3-force per-tick: vx *= velocityDecay; x += vx.
50
+ var v: vec3<f32> = velocities[i].xyz * params.velocityDecay;
51
+
52
+ // Clamp velocity magnitude to maxVel (when maxVel > 0). Mirrors WebGL.
53
+ // CRITICAL: the clamp only affects POSITION update this tick; the stored
54
+ // velocity must remain unclamped so momentum can build across ticks (this
55
+ // matches the legacy WebGL FBO pipeline where update-position.frag.glsl
56
+ // clamps its local copy but velocity-decay.frag.glsl's output to the
57
+ // velocity texture is NEVER overwritten by update-position). If we clamp
58
+ // the stored velocity too, every tick the integrator throws away most of
59
+ // the accumulated velocity from forces and nodes barely move from their
60
+ // phyllotaxis initial positions.
61
+ var posDelta: vec3<f32> = v;
62
+ if (params.maxVel > 0.0) {
63
+ let mag = length(posDelta);
64
+ if (mag > params.maxVel) {
65
+ posDelta = posDelta * (params.maxVel / mag);
66
+ }
67
+ }
68
+
69
+ var p: vec3<f32> = positions[i].xyz + posDelta;
70
+
71
+ // Mask unused dimensions (2D simulation: zero out z; 1D: also y).
72
+ if (params.nDim < 3.0) {
73
+ p.z = 0.0;
74
+ v.z = 0.0;
75
+ }
76
+ if (params.nDim < 2.0) {
77
+ p.y = 0.0;
78
+ v.y = 0.0;
79
+ }
80
+
81
+ positions[i] = vec4<f32>(p, positions[i].w);
82
+ // Store the decayed-but-UNCLAMPED velocity so momentum carries to next tick.
83
+ velocities[i] = vec4<f32>(v, 0.0);
84
+ }
85
+ `,X=16,Y=16,ue=4,be=16,ye=64;function ve(e,n=3,r={}){let t=e,i=t.length,a=n,s=1,o=.001,u=0,l=1-Math.pow(o,1/300),m=.6,h=0,d=Math.random,b=new Map,P=new Map,g=null,f=null,p=null,x=null,B=null,G=null,F=null,z=null,w=null,D=null,T=!1,U=!1,$=!1;oe(t,a,d),(r.device||re())&&Q();async function Q(){try{f=r.device?await r.device:await he({preferHighPerformance:r.preferHighPerformance}),H(),N(),j(),b.forEach(c=>v(c)),T=!0,C("ready")}catch(c){console.error("[webgpuForceSimulation] device init failed:",c)}}function j(){if(!f||!p||!x||!B)return;let{device:c}=f;z?.destroy(),z=c.createBuffer({label:"integrate-params",size:be,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let y=c.createShaderModule({label:"integrate-shader",code:ge});w=c.createComputePipeline({label:"integrate-pipeline",layout:"auto",compute:{module:y,entryPoint:"main"}}),D=c.createBindGroup({label:"integrate-bind-group",layout:w.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:p}},{binding:1,resource:{buffer:x}},{binding:2,resource:{buffer:B}},{binding:3,resource:{buffer:z}}]})}function Z(){if(!f||!z)return;let c=new Float32Array([m,a,i,h]);f.device.queue.writeBuffer(z,0,c)}function H(){if(!f)return;let{device:c}=f;p?.destroy(),x?.destroy(),B?.destroy(),G?.destroy(),F?.destroy(),p=c.createBuffer({label:"positions",size:i*X,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),x=c.createBuffer({label:"velocities",size:i*Y,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),B=c.createBuffer({label:"pinned",size:i*ue,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),G=c.createBuffer({label:"readback",size:i*X,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),F=c.createBuffer({label:"readback-velocity",size:i*Y,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST})}function N(){if(!f||!p||!x||!B)return;let{device:c}=f,y=new Float32Array(i*4),M=new Float32Array(i*4),A=new Float32Array(i);for(let _=0;_<i;_++){let S=t[_];y[_*4+0]=S.x??0,y[_*4+1]=S.y??0,y[_*4+2]=S.z??0,y[_*4+3]=_,M[_*4+0]=S.vx??0,M[_*4+1]=S.vy??0,M[_*4+2]=S.vz??0,A[_]=S.fx!=null||S.fy!=null||S.fz!=null?1:0}c.queue.writeBuffer(p,0,y),c.queue.writeBuffer(x,0,M),c.queue.writeBuffer(B,0,A)}function v(c){if(!f||!p||!x||!B)return;let y={device:f.device,nodeCount:i,nDim:a,positionBuffer:p,velocityBuffer:x,pinnedBuffer:B};c.initGPU(y)}function C(c){let y=P.get(c);if(y)for(let M of y)M()}function k(c=1){if(!T||!f||!w||!D)return;let{device:y}=f;for(let M=0;M<c;M++){if(s<o){C("end");return}Z();let A=y.createCommandEncoder({label:"tick"});b.forEach(S=>S.apply(s,A));let _=A.beginComputePass({label:"integrate"});_.setPipeline(w),_.setBindGroup(0,D),_.dispatchWorkgroups(Math.ceil(i/ye)),_.end(),y.queue.submit([A.finish()]),s=s+(u-s)*l,C("tick")}}async function q(){if(!(!f||!p||!G)&&!U){U=!0;try{let{device:c}=f,y=c.createCommandEncoder({label:"readback"});y.copyBufferToBuffer(p,0,G,0,i*X),c.queue.submit([y.finish()]);try{await G.mapAsync(GPUMapMode.READ,0,i*X)}catch(A){let _=A?.name;if(_==="AbortError"||_==="OperationError")return;throw A}if(!G)return;let M=new Float32Array(G.getMappedRange(0,i*X));if(globalThis.__webgpuPathASkip===!0){(!g||g.length<M.length)&&(g=new Float32Array(M.length)),g.set(M),G.unmap();return}for(let A=0;A<i;A++){let _=A*4,S=t[A];S.fx==null&&(S.x=M[_]),a>1&&S.fy==null&&(S.y=M[_+1]),a>2&&S.fz==null?S.z=M[_+2]:a<=2&&(S.z=0)}G.unmap()}finally{U=!1}}}async function I(){if(!f||!x||!F)return new Float32Array(0);let{device:c}=f,y=c.createCommandEncoder({label:"readback-vel"});y.copyBufferToBuffer(x,0,F,0,i*Y),c.queue.submit([y.finish()]);try{await F.mapAsync(GPUMapMode.READ,0,i*Y)}catch(_){if(_?.name==="AbortError")return new Float32Array(0);throw _}if(!F)return new Float32Array(0);let M=new Float32Array(F.getMappedRange(0,i*Y)),A=new Float32Array(M);return F.unmap(),A}return{tick(c){return k(c??1),this},restart(){return s=1,this},stop(){return this},alpha(c){return arguments.length===0?s:(s=+c,this)},alphaMin(c){return arguments.length===0?o:(o=+c,this)},alphaDecay(c){return arguments.length===0?l:(l=+c,this)},velocityDecay(c){return arguments.length===0?m:(m=+c,this)},alphaTarget(c){return arguments.length===0?u:(u=+c,this)},maxVel(c){return arguments.length===0?h:(h=+c,this)},uploadPosition(c,y,M,A){if(!f||!p||c<0||c>=i)return;let _=c*X,S=new Float32Array([y,M,A,c]);f.device.queue.writeBuffer(p,_,S);let O=t[c];O&&(O.x=y,O.y=M,O.z=A)},uploadVelocity(c,y,M,A){if(!f||!x||c<0||c>=i)return;let _=c*Y,S=new Float32Array([y,M,A,0]);f.device.queue.writeBuffer(x,_,S);let O=t[c];O&&(O.vx=y,O.vy=M,O.vz=A)},uploadPinned(c,y){if(!f||!B||c<0||c>=i)return;let M=c*ue;f.device.queue.writeBuffer(B,M,new Float32Array([y?1:0]))},nodes(c){return arguments.length===0?t:(t=c,i=t.length,oe(t,a,d),f&&(H(),N(),j(),b.forEach(y=>v(y))),this)},force(c,y){return arguments.length===1?b.get(c):(y==null?b.delete(c):(y.initialize(t,d,a),b.set(c,y),f&&v(y)),this)},numDimensions(c){return arguments.length===0?a:(a=+c,Z(),b.forEach(y=>y.initialize(t,d,a)),this)},on(c,y){let M=P.get(c);return M||(M=[],P.set(c,M)),M.push(y),this},dispose(){p?.destroy(),x?.destroy(),B?.destroy(),G?.destroy(),F?.destroy(),z?.destroy(),p=x=B=G=null,F=null,z=null,w=null,D=null,b.forEach(c=>c.dispose?.()),b.clear(),T=!1},isReady(){return T},readPositions(){return q()},readVelocities(){return I()},getDevice(){return f?.device??null},getPositionBuffer(){return p}}}var xe=`// forceCenter \u2014 pass 1 of 2: parallel reduce centroid \u2192 shift vector.
86
+ //
87
+ // Computes mean(positions) across all nodes inside a single workgroup using
88
+ // shared memory, then writes (mean - target) * strength to shift[0].
89
+ //
90
+ // Single workgroup with 64 threads handles up to ~10M nodes via per-thread
91
+ // striding before the tree reduce. For very large N this is fine for forceCenter
92
+ // since it's invoked once per tick (not per-edge / per-pair like manyBody).
93
+ //
94
+ // f32 atomics aren't supported in WebGPU, so a single-workgroup reduce is the
95
+ // cleanest scalar-precise approach without multi-pass scaffolding.
96
+ //
97
+ // Layout:
98
+ // group(0)
99
+ // binding(0) positions array<vec4<f32>> read
100
+ // binding(1) shift array<vec4<f32>> read_write (1 element)
101
+ // binding(2) params CenterParams uniform
102
+
103
+ struct CenterParams {
104
+ nodeCount: f32,
105
+ nDim: f32,
106
+ strength: f32,
107
+ _pad0: f32,
108
+ targetX: f32,
109
+ targetY: f32,
110
+ targetZ: f32,
111
+ _pad1: f32,
112
+ }
113
+
114
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
115
+ @group(0) @binding(1) var<storage, read_write> shift: array<vec4<f32>>;
116
+ @group(0) @binding(2) var<uniform> params: CenterParams;
117
+
118
+ var<workgroup> partial: array<vec3<f32>, 64>;
119
+
120
+ @compute @workgroup_size(64)
121
+ fn main(@builtin(local_invocation_id) lid: vec3<u32>) {
122
+ let tid: u32 = lid.x;
123
+ let n: u32 = u32(params.nodeCount);
124
+
125
+ // Strided sum: each thread sums positions[tid], positions[tid+64], ...
126
+ var sum: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);
127
+ var i: u32 = tid;
128
+ loop {
129
+ if (i >= n) { break; }
130
+ sum = sum + positions[i].xyz;
131
+ i = i + 64u;
132
+ }
133
+ partial[tid] = sum;
134
+ workgroupBarrier();
135
+
136
+ // Unrolled tree reduce 64 \u2192 1.
137
+ if (tid < 32u) { partial[tid] = partial[tid] + partial[tid + 32u]; }
138
+ workgroupBarrier();
139
+ if (tid < 16u) { partial[tid] = partial[tid] + partial[tid + 16u]; }
140
+ workgroupBarrier();
141
+ if (tid < 8u) { partial[tid] = partial[tid] + partial[tid + 8u]; }
142
+ workgroupBarrier();
143
+ if (tid < 4u) { partial[tid] = partial[tid] + partial[tid + 4u]; }
144
+ workgroupBarrier();
145
+ if (tid < 2u) { partial[tid] = partial[tid] + partial[tid + 2u]; }
146
+ workgroupBarrier();
147
+ if (tid < 1u) { partial[tid] = partial[tid] + partial[tid + 1u]; }
148
+ workgroupBarrier();
149
+
150
+ if (tid == 0u) {
151
+ let mean: vec3<f32> = partial[0] / f32(n);
152
+ let centerTarget: vec3<f32> = vec3<f32>(params.targetX, params.targetY, params.targetZ);
153
+ var s: vec3<f32> = (mean - centerTarget) * params.strength;
154
+ // Mask unused dimensions so 2D/1D shifts don't bleed into higher axes.
155
+ if (params.nDim < 3.0) { s.z = 0.0; }
156
+ if (params.nDim < 2.0) { s.y = 0.0; }
157
+ shift[0] = vec4<f32>(s, 0.0);
158
+ }
159
+ }
160
+ `,Be=`// forceCenter \u2014 pass 2 of 2: subtract shift from every node's position.
161
+ //
162
+ // Mirrors d3-force-3d center.js: \`node.x -= shift\`. Pinned nodes are skipped.
163
+ // One invocation per node.
164
+ //
165
+ // Layout:
166
+ // group(0)
167
+ // binding(0) positions array<vec4<f32>> read_write
168
+ // binding(1) pinned array<f32> read
169
+ // binding(2) shift array<vec4<f32>> read (1 element, written by reduce pass)
170
+ // binding(3) params ApplyParams uniform
171
+
172
+ struct ApplyParams {
173
+ nodeCount: f32,
174
+ nDim: f32,
175
+ _pad0: f32,
176
+ _pad1: f32,
177
+ }
178
+
179
+ @group(0) @binding(0) var<storage, read_write> positions: array<vec4<f32>>;
180
+ @group(0) @binding(1) var<storage, read> pinned: array<f32>;
181
+ @group(0) @binding(2) var<storage, read> shift: array<vec4<f32>>;
182
+ @group(0) @binding(3) var<uniform> params: ApplyParams;
183
+
184
+ @compute @workgroup_size(64)
185
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
186
+ let i: u32 = gid.x;
187
+ if (f32(i) >= params.nodeCount) { return; }
188
+ if (pinned[i] > 0.5) { return; }
189
+
190
+ var p: vec3<f32> = positions[i].xyz - shift[0].xyz;
191
+ if (params.nDim < 3.0) { p.z = 0.0; }
192
+ if (params.nDim < 2.0) { p.y = 0.0; }
193
+ positions[i] = vec4<f32>(p, positions[i].w);
194
+ }
195
+ `,Pe=16,Me=32,_e=16,we=64;function Ce(e=0,n=0,r=0){let t=e,i=n,a=r,s=1,o=3,u=0,l=null,m=null,h=null,d=null,b=null,P=null,g=null,f=null;function p(w,D,T){o=T}function x(w){l=w.device,u=w.nodeCount,o=w.nDim,m?.destroy(),m=l.createBuffer({label:"center-shift",size:Pe,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),h?.destroy(),h=l.createBuffer({label:"center-reduce-params",size:Me,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),d?.destroy(),d=l.createBuffer({label:"center-apply-params",size:_e,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let D=l.createShaderModule({label:"center-reduce-shader",code:xe});b=l.createComputePipeline({label:"center-reduce-pipeline",layout:"auto",compute:{module:D,entryPoint:"main"}});let T=l.createShaderModule({label:"center-apply-shader",code:Be});P=l.createComputePipeline({label:"center-apply-pipeline",layout:"auto",compute:{module:T,entryPoint:"main"}}),g=l.createBindGroup({label:"center-reduce-bind-group",layout:b.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:w.positionBuffer}},{binding:1,resource:{buffer:m}},{binding:2,resource:{buffer:h}}]}),f=l.createBindGroup({label:"center-apply-bind-group",layout:P.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:w.positionBuffer}},{binding:1,resource:{buffer:w.pinnedBuffer}},{binding:2,resource:{buffer:m}},{binding:3,resource:{buffer:d}}]})}function B(){if(!l||!h||!d)return;let w=new Float32Array([u,o,s,0,t,i,a,0]);l.queue.writeBuffer(h,0,w);let D=new Float32Array([u,o,0,0]);l.queue.writeBuffer(d,0,D)}function G(w,D){if(!b||!P||!g||!f||u===0)return;B();let T=D.beginComputePass({label:"center-reduce"});T.setPipeline(b),T.setBindGroup(0,g),T.dispatchWorkgroups(1),T.end();let U=D.beginComputePass({label:"center-apply"});U.setPipeline(P),U.setBindGroup(0,f),U.dispatchWorkgroups(Math.ceil(u/we)),U.end()}function F(){m?.destroy(),h?.destroy(),d?.destroy(),m=h=d=null,b=P=null,g=f=null,l=null}let z={initialize:p,initGPU:x,apply:G,dispose:F,x(w){return arguments.length===0?t:(t=+w,z)},y(w){return arguments.length===0?i:(i=+w,z)},z(w){return arguments.length===0?a:(a=+w,z)},strength(w){return arguments.length===0?s:(s=+w,z)}};return z}var ke=`// Per-axis attractive force (forceX / forceY / forceZ).
196
+ //
197
+ // One invocation per node. Adds \`(target - position[axis]) * strength * alpha\`
198
+ // to that node's velocity along the configured axis only \u2014 other axes untouched.
199
+ // Axis is selected by uniform: 0=X, 1=Y, 2=Z.
200
+ //
201
+ // d3-force-3d equivalents: x.js, y.js, z.js. All three have identical structure
202
+ // (target accessor + strength accessor + per-tick velocity update on one axis).
203
+ // We collapse to a single shader keyed on axis to avoid 3\xD7 duplication.
204
+ //
205
+ // Layout:
206
+ // group(0)
207
+ // binding(0) positions array<vec4<f32>> read
208
+ // binding(1) velocities array<vec4<f32>> read_write
209
+ // binding(2) params PositionForceParams uniform
210
+
211
+ struct PositionForceParams {
212
+ axis: f32, // 0=X, 1=Y, 2=Z
213
+ targetPos: f32,
214
+ strength: f32,
215
+ alpha: f32,
216
+ nodeCount: f32,
217
+ _pad0: f32,
218
+ _pad1: f32,
219
+ _pad2: f32,
220
+ }
221
+
222
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
223
+ @group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
224
+ @group(0) @binding(2) var<uniform> params: PositionForceParams;
225
+
226
+ @compute @workgroup_size(64)
227
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
228
+ let i: u32 = gid.x;
229
+ if (f32(i) >= params.nodeCount) { return; }
230
+
231
+ let pos: vec3<f32> = positions[i].xyz;
232
+ var vel: vec3<f32> = velocities[i].xyz;
233
+
234
+ if (params.axis < 0.5) {
235
+ vel.x = vel.x + (params.targetPos - pos.x) * params.strength * params.alpha;
236
+ } else if (params.axis < 1.5) {
237
+ vel.y = vel.y + (params.targetPos - pos.y) * params.strength * params.alpha;
238
+ } else {
239
+ vel.z = vel.z + (params.targetPos - pos.z) * params.strength * params.alpha;
240
+ }
241
+
242
+ velocities[i] = vec4<f32>(vel, velocities[i].w);
243
+ }
244
+ `,Ie=32,Se=64;function ae(e,n){let r=n,t=.1,i=0,a=null,s=null,o=null,u=null;function l(){}function m(g){a=g.device,i=g.nodeCount,s?.destroy(),s=a.createBuffer({label:`position-force-${e}-params`,size:Ie,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let f=a.createShaderModule({label:`position-force-${e}-shader`,code:ke});o=a.createComputePipeline({label:`position-force-${e}-pipeline`,layout:"auto",compute:{module:f,entryPoint:"main"}}),u=a.createBindGroup({label:`position-force-${e}-bind-group`,layout:o.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:g.positionBuffer}},{binding:1,resource:{buffer:g.velocityBuffer}},{binding:2,resource:{buffer:s}}]})}function h(g){if(!a||!s)return;let f=new Float32Array([e,r,t,g,i,0,0,0]);a.queue.writeBuffer(s,0,f)}function d(g,f){if(!o||!u||i===0)return;h(g);let p=f.beginComputePass({label:`position-force-${e}`});p.setPipeline(o),p.setBindGroup(0,u),p.dispatchWorkgroups(Math.ceil(i/Se)),p.end()}function b(){s?.destroy(),s=null,o=null,u=null,a=null}let P={initialize:l,initGPU:m,apply:d,dispose:b,strength(g){return arguments.length===0?t:(t=+g,P)},target(g){return arguments.length===0?r:(r=+g,P)}};return P}function Ae(e=0){return ae(0,e)}function Fe(e=0){return ae(1,e)}function ze(e=0){return ae(2,e)}var Te=`// forceLink \u2014 per-edge spring constraint.
245
+ //
246
+ // One invocation per edge. For each edge (s, t), computes a delta toward the
247
+ // configured \`linkDistance\` and accumulates contributions into an integer
248
+ // accumulator buffer (atomicAdd-safe). A second compute pass (apply) drains the
249
+ // accumulator into the float velocity buffer, dividing by the scale factor.
250
+ //
251
+ // f32 atomics aren't in WebGPU yet \u2014 we quantize to i32 via FIXED_POINT_SCALE.
252
+ // At 1e6 scale + per-edge magnitudes well under |10|, range fits comfortably
253
+ // in i32 even with thousands of edges sharing a node.
254
+ //
255
+ // d3-force formula (link.js):
256
+ // bias_s = countSrc / (countSrc + countTgt) (source's share of pull)
257
+ // delta = (current_dist - linkDistance) * strength * alpha / current_dist
258
+ // src.v += (t - s) * delta * (1 - bias_s)
259
+ // tgt.v -= (t - s) * delta * bias_s
260
+ //
261
+ // Jiggle: if current_dist == 0, perturb to break symmetry.
262
+ //
263
+ // Layout:
264
+ // group(0)
265
+ // binding(0) positions array<vec4<f32>> read
266
+ // binding(1) velAccum array<atomic<i32>> read_write (3 \xD7 nodeCount slots)
267
+ // binding(2) edges array<vec4<f32>> read (src_idx, tgt_idx, biasSrc, distance)
268
+ // binding(3) params LinkParams uniform
269
+ // binding(4) strengths array<f32> read (per-edge strength = defaultStrength * strengthScale)
270
+ // binding(5) velocities array<vec4<f32>> read (for velocity-anticipated half-step: pos + vel)
271
+
272
+ const FIXED_POINT_SCALE: f32 = 1048576.0; // 2^20
273
+
274
+ struct LinkParams {
275
+ edgeCount: f32,
276
+ _pad1: f32, // was: strength (per-edge strengths buffer replaces this)
277
+ alpha: f32,
278
+ _pad0: f32,
279
+ }
280
+
281
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
282
+ @group(0) @binding(1) var<storage, read_write> velAccum: array<atomic<i32>>;
283
+ @group(0) @binding(2) var<storage, read> edges: array<vec4<f32>>;
284
+ @group(0) @binding(3) var<uniform> params: LinkParams;
285
+ @group(0) @binding(4) var<storage, read> strengths: array<f32>; // per-edge default strength
286
+ @group(0) @binding(5) var<storage, read> velocities: array<vec4<f32>>; // for velocity-anticipated half-step
287
+
288
+ @compute @workgroup_size(64)
289
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
290
+ let e: u32 = gid.x;
291
+ if (f32(e) >= params.edgeCount) { return; }
292
+
293
+ let edge = edges[e];
294
+ let sIdx: u32 = u32(edge.x);
295
+ let tIdx: u32 = u32(edge.y);
296
+ let biasSrc: f32 = edge.z;
297
+ let linkDistance: f32 = edge.w;
298
+
299
+ let src = positions[sIdx].xyz + velocities[sIdx].xyz; // velocity-anticipated half-step
300
+ let tgt = positions[tIdx].xyz + velocities[tIdx].xyz; // (mirrors d3 link.js:37-39)
301
+ var d: vec3<f32> = tgt - src;
302
+
303
+ // Jiggle when zero-vector (d3-force jiggle: \xB10.5e-6 per axis, deterministic
304
+ // here by using edge index as a phase shift \u2014 good enough for breaking ties).
305
+ if (length(d) < 1e-12) {
306
+ let phase = f32(e) * 0.123456;
307
+ d = vec3<f32>(sin(phase) * 1e-6, cos(phase) * 1e-6, sin(phase * 2.0) * 1e-6);
308
+ }
309
+
310
+ let dist: f32 = length(d);
311
+ let stretch: f32 = (dist - linkDistance) * strengths[e] * params.alpha / dist;
312
+ let pull: vec3<f32> = d * stretch;
313
+
314
+ let srcShare: vec3<f32> = pull * (1.0 - biasSrc);
315
+ let tgtShare: vec3<f32> = pull * biasSrc;
316
+
317
+ // Quantize and atomic-add into the integer accumulator. Layout: per node,
318
+ // three consecutive i32 slots (x, y, z).
319
+ atomicAdd(&velAccum[sIdx * 3u + 0u], i32(srcShare.x * FIXED_POINT_SCALE));
320
+ atomicAdd(&velAccum[sIdx * 3u + 1u], i32(srcShare.y * FIXED_POINT_SCALE));
321
+ atomicAdd(&velAccum[sIdx * 3u + 2u], i32(srcShare.z * FIXED_POINT_SCALE));
322
+ atomicSub(&velAccum[tIdx * 3u + 0u], i32(tgtShare.x * FIXED_POINT_SCALE));
323
+ atomicSub(&velAccum[tIdx * 3u + 1u], i32(tgtShare.y * FIXED_POINT_SCALE));
324
+ atomicSub(&velAccum[tIdx * 3u + 2u], i32(tgtShare.z * FIXED_POINT_SCALE));
325
+ }
326
+ `,Ge=`// forceLink pass 2: drain the i32 atomic accumulator into f32 velocities.
327
+ //
328
+ // One invocation per node. Reads the 3 i32 slots populated by link-force.wgsl,
329
+ // converts back to f32 (divides by FIXED_POINT_SCALE), adds to velocity, then
330
+ // zeros the accumulator for the next tick.
331
+ //
332
+ // Layout:
333
+ // group(0)
334
+ // binding(0) velocities array<vec4<f32>> read_write
335
+ // binding(1) velAccum array<atomic<i32>> read_write
336
+ // binding(2) params DrainParams uniform
337
+
338
+ const FIXED_POINT_SCALE: f32 = 1048576.0; // 2^20; must match link-force.wgsl
339
+
340
+ struct DrainParams {
341
+ nodeCount: f32,
342
+ _pad0: f32,
343
+ _pad1: f32,
344
+ _pad2: f32,
345
+ }
346
+
347
+ @group(0) @binding(0) var<storage, read_write> velocities: array<vec4<f32>>;
348
+ @group(0) @binding(1) var<storage, read_write> velAccum: array<atomic<i32>>;
349
+ @group(0) @binding(2) var<uniform> params: DrainParams;
350
+
351
+ @compute @workgroup_size(64)
352
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
353
+ let i: u32 = gid.x;
354
+ if (f32(i) >= params.nodeCount) { return; }
355
+
356
+ let ax = atomicExchange(&velAccum[i * 3u + 0u], 0);
357
+ let ay = atomicExchange(&velAccum[i * 3u + 1u], 0);
358
+ let az = atomicExchange(&velAccum[i * 3u + 2u], 0);
359
+
360
+ let delta = vec3<f32>(f32(ax), f32(ay), f32(az)) / FIXED_POINT_SCALE;
361
+ velocities[i] = vec4<f32>(velocities[i].xyz + delta, velocities[i].w);
362
+ }
363
+ `,qe=12,Le=16,De=16,le=64;function Ee(e){return()=>e}function Ue(e=[]){let n=e,r=new Int32Array(0),t=30,i=[],a=0,s=null,o=null,u=null,l=null,m=null,h=null,d=null,b=null,P=null,g=null,f=0,p=new Float32Array(0),x=null,B=null;function G(v){let C=v.source,k=v.target,q=Math.min(r[C]??1,r[k]??1);return q>0?1/q:1}let F=G;function z(v,C,k){i=v}function w(){let v=new Map;for(let I=0;I<i.length;I++){let E=i[I];E.id!=null&&v.set(E.id,I),E.index!=null&&v.set(E.index,I)}let C=new Int32Array(i.length),k=[];for(let I=0;I<n.length;I++){let E=n[I],c=D(E.source,v),y=D(E.target,v);c<0||y<0||(C[c]++,C[y]++,k.push({source:c,target:y,index:I}))}r=C;let q=new Float32Array(k.length*4);p=new Float32Array(k.length);for(let I=0;I<k.length;I++){let E=k[I].source,c=k[I].target,y=C[E]+C[c],M=y>0?C[E]/y:.5;q[I*4+0]=E,q[I*4+1]=c,q[I*4+2]=M,q[I*4+3]=t,p[I]=+F(k[I],I,k)}return f=k.length,q}function D(v,C){if(typeof v=="object"&&v!==null){let k=v;return k.index!=null?k.index:k.id!=null?C.get(k.id)??-1:-1}return C.get(v)??-1}function T(){if(!s)return;let v=w();if(o?.destroy(),u?.destroy(),v.length===0){o=null,u=null;return}o=s.createBuffer({label:"link-edges",size:v.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),s.queue.writeBuffer(o,0,v.buffer,v.byteOffset,v.byteLength),u=s.createBuffer({label:"link-strengths",size:Math.max(p.byteLength,4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),s.queue.writeBuffer(u,0,p.buffer,p.byteOffset,p.byteLength),B&&x&&$(B,x)}function U(v){s=v.device,a=v.nodeCount,l?.destroy(),l=s.createBuffer({label:"link-vel-accum",size:a*qe,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});let C=new Int32Array(a*3);s.queue.writeBuffer(l,0,C.buffer,0,C.byteLength),m?.destroy(),m=s.createBuffer({label:"link-params",size:Le,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),h?.destroy(),h=s.createBuffer({label:"link-drain-params",size:De,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let k=s.createShaderModule({label:"link-force-shader",code:Te});d=s.createComputePipeline({label:"link-force-pipeline",layout:"auto",compute:{module:k,entryPoint:"main"}});let q=s.createShaderModule({label:"link-drain-shader",code:Ge});b=s.createComputePipeline({label:"link-drain-pipeline",layout:"auto",compute:{module:q,entryPoint:"main"}}),T(),$(v.positionBuffer,v.velocityBuffer)}function $(v,C){!s||!d||!b||!l||!m||!h||(x=C,B=v,o&&u?P=s.createBindGroup({label:"link-force-bind-group",layout:d.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:v}},{binding:1,resource:{buffer:l}},{binding:2,resource:{buffer:o}},{binding:3,resource:{buffer:m}},{binding:4,resource:{buffer:u}},{binding:5,resource:{buffer:C}}]}):P=null,g=s.createBindGroup({label:"link-drain-bind-group",layout:b.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:C}},{binding:1,resource:{buffer:l}},{binding:2,resource:{buffer:h}}]}))}function Q(){T()}function j(v){if(!s||!m||!h)return;let C=new Float32Array([f,0,v,0]);s.queue.writeBuffer(m,0,C);let k=new Float32Array([a,0,0,0]);s.queue.writeBuffer(h,0,k)}function Z(v,C){if(!d||!b||!g||a===0)return;if(j(v),P&&f>0){let q=C.beginComputePass({label:"link-force"});q.setPipeline(d),q.setBindGroup(0,P),q.dispatchWorkgroups(Math.ceil(f/le)),q.end()}let k=C.beginComputePass({label:"link-drain"});k.setPipeline(b),k.setBindGroup(0,g),k.dispatchWorkgroups(Math.ceil(a/le)),k.end()}function H(){o?.destroy(),u?.destroy(),l?.destroy(),m?.destroy(),h?.destroy(),o=u=l=m=h=null,d=b=null,P=g=null,x=null,B=null,s=null}let N={initialize:z,initGPU:U,apply:Z,dispose:H,links(v){return arguments.length===0?n:(n=v,s&&T(),N)},strength(v){return arguments.length===0?F:(F=typeof v=="function"?v:Ee(+v),s&&T(),N)},distance(v){return arguments.length===0?t:(t=+v,s&&T(),N)},rebuildEdgeBuffer:Q};return N}var Oe=`// forceManyBody \u2014 O(N\xB2) brute-force pairwise repulsion/attraction.
364
+ //
365
+ // One invocation per query node. Each thread iterates over ALL other nodes
366
+ // and accumulates per-pair \`c / l\xB2 * (xyz)\` velocity contributions. Suitable
367
+ // for \u226410k nodes at 60fps on modern GPUs; falls off sharply above that.
368
+ //
369
+ // This is the correctness baseline before the LBVH-style octree lands \u2014
370
+ // equivalent to d3-octree's leaf-level pairwise behavior over the full set.
371
+ // No COM aggregation \u2192 no axis-aligned cross-star artifact.
372
+ //
373
+ // d3-force formula (manyBody.js):
374
+ // for each pair (i, j), i != j:
375
+ // x = j.x - i.x, y = j.y - i.y, z = j.z - i.z
376
+ // if (x == 0) x = jiggle(); l += x\xB2
377
+ // if (y == 0) y = jiggle(); l += y\xB2
378
+ // if (z == 0) z = jiggle(); l += z\xB2
379
+ // l = x\xB2 + y\xB2 + z\xB2
380
+ // if (l < distanceMin\xB2) l = sqrt(distanceMin\xB2 * l)
381
+ // if (l >= distanceMax\xB2) continue
382
+ // i.vx += x * c / l
383
+ //
384
+ // Layout:
385
+ // group(0)
386
+ // binding(0) positions array<vec4<f32>> read
387
+ // binding(1) velocities array<vec4<f32>> read_write
388
+ // binding(2) randoms array<vec4<f32>> read (per-node random jiggle source)
389
+ // binding(3) params ManyBodyParams uniform
390
+
391
+ struct ManyBodyParams {
392
+ strength: f32,
393
+ alpha: f32,
394
+ distanceMin2: f32,
395
+ distanceMax2: f32,
396
+ nodeCount: f32,
397
+ _pad0: f32,
398
+ _pad1: f32,
399
+ _pad2: f32,
400
+ }
401
+
402
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
403
+ @group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
404
+ @group(0) @binding(2) var<storage, read> randoms: array<vec4<f32>>;
405
+ @group(0) @binding(3) var<uniform> params: ManyBodyParams;
406
+
407
+ fn jiggle(seed: f32) -> f32 {
408
+ return (seed - 0.5) * 1e-6;
409
+ }
410
+
411
+ @compute @workgroup_size(64)
412
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
413
+ let i: u32 = gid.x;
414
+ let n: u32 = u32(params.nodeCount);
415
+ if (f32(i) >= params.nodeCount) { return; }
416
+
417
+ let pi = positions[i].xyz;
418
+ let ri = randoms[i].xyz;
419
+ var accum = vec3<f32>(0.0, 0.0, 0.0);
420
+
421
+ for (var j: u32 = 0u; j < n; j = j + 1u) {
422
+ if (j == i) { continue; }
423
+ var d: vec3<f32> = positions[j].xyz - pi;
424
+
425
+ // Jiggle exact zeros (rare; happens with overlapping init positions).
426
+ if (d.x == 0.0) { d.x = jiggle(ri.x); }
427
+ if (d.y == 0.0) { d.y = jiggle(ri.y); }
428
+ if (d.z == 0.0) { d.z = jiggle(ri.z); }
429
+
430
+ var l: f32 = d.x * d.x + d.y * d.y + d.z * d.z;
431
+ if (l < params.distanceMin2) { l = sqrt(params.distanceMin2 * l); }
432
+ if (l >= params.distanceMax2) { continue; }
433
+
434
+ let c: f32 = params.alpha * params.strength / l;
435
+ accum = accum + d * c;
436
+ }
437
+
438
+ velocities[i] = vec4<f32>(velocities[i].xyz + accum, velocities[i].w);
439
+ }
440
+ `,Re=32,Ne=64,Xe=16;function qn(){let e=-30,n=1,r=1/0,t=0,i=Math.random,a=null,s=null,o=null,u=null,l=null;function m(f,p,x){i=p}function h(f){a=f.device,t=f.nodeCount;let p=new Float32Array(t*4);for(let B=0;B<t;B++)p[B*4+0]=i(),p[B*4+1]=i(),p[B*4+2]=i(),p[B*4+3]=0;s?.destroy(),s=a.createBuffer({label:"manybody-randoms",size:t*Xe,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),a.queue.writeBuffer(s,0,p),o?.destroy(),o=a.createBuffer({label:"manybody-params",size:Re,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let x=a.createShaderModule({label:"manybody-bruteforce-shader",code:Oe});u=a.createComputePipeline({label:"manybody-bruteforce-pipeline",layout:"auto",compute:{module:x,entryPoint:"main"}}),l=a.createBindGroup({label:"manybody-bind-group",layout:u.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:f.positionBuffer}},{binding:1,resource:{buffer:f.velocityBuffer}},{binding:2,resource:{buffer:s}},{binding:3,resource:{buffer:o}}]})}function d(f){if(!a||!o)return;let p=n*n,x=r===1/0?1e30:r*r,B=new Float32Array([e,f,p,x,t,0,0,0]);a.queue.writeBuffer(o,0,B)}function b(f,p){if(!u||!l||t===0)return;d(f);let x=p.beginComputePass({label:"manybody-bruteforce"});x.setPipeline(u),x.setBindGroup(0,l),x.dispatchWorkgroups(Math.ceil(t/Ne)),x.end()}function P(){s?.destroy(),o?.destroy(),s=o=null,u=null,l=null,a=null}let g={initialize:m,initGPU:h,apply:b,dispose:P,strength(f){return arguments.length===0?e:(e=+f,g)},distanceMin(f){return arguments.length===0?n:(n=+f,g)},distanceMax(f){return arguments.length===0?r:(r=+f,g)}};return g}var fe=64,R=32,Ye=.9;function We(e){return e<=1?1:1<<Math.ceil(Math.log2(e))}function je(e,n,r){let t=n,i=We(t),a=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,s=e.createBuffer({label:"lbvh-morton",size:i*4,usage:a}),o=e.createBuffer({label:"lbvh-sortedIndices",size:i*4,usage:a}),u=e.createBuffer({label:"lbvh-internal",size:Math.max(1,t-1)*16,usage:a}),l=e.createBuffer({label:"lbvh-parent",size:Math.max(1,t-1)*4,usage:a}),m=e.createBuffer({label:"lbvh-aabb",size:Math.max(1,2*t-1)*32,usage:a}),h=e.createBuffer({label:"lbvh-com",size:Math.max(1,2*t-1)*16,usage:a}),d=e.createBuffer({label:"lbvh-depth",size:Math.max(1,t-1)*4,usage:a}),b=e.createBuffer({label:"lbvh-bounds",size:32,usage:a}),P=e.createBuffer({label:"lbvh-queueA",size:Math.max(1,t-1)*4,usage:a}),g=e.createBuffer({label:"lbvh-queueB",size:Math.max(1,t-1)*4,usage:a}),f=e.createBuffer({label:"lbvh-frontier",size:(r+1)*4,usage:a}),p=e.createBuffer({label:"lbvh-root",size:4,usage:a});return{paddedN:i,morton:s,sortedIndices:o,internal:u,parent:l,aabb:m,com:h,depth:d,bounds:b,depthQueueA:P,depthQueueB:g,frontierCounts:f,root:p,dispose(){for(let x of[s,o,u,l,m,h,d,b,P,g,f,p])x.destroy()}}}var se=`// P1: scene AABB via atomicMin/atomicMax on i32 bit-reinterpretation of f32 positions.
441
+ // Uses ordered-i32 trick: for positive floats, integer bit pattern preserves order;
442
+ // for negative, flipping all bits restores order. Inverse on read recovers f32.
443
+
444
+ struct BoundsParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
445
+
446
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
447
+ @group(0) @binding(1) var<storage, read_write> bounds: array<atomic<i32>, 6>;
448
+ @group(0) @binding(2) var<uniform> params: BoundsParams;
449
+
450
+ fn floatToOrderedInt(f: f32) -> i32 {
451
+ let bits = bitcast<i32>(f);
452
+ return select(bits ^ 0x7FFFFFFF, bits, bits >= 0);
453
+ }
454
+
455
+ @compute @workgroup_size(64)
456
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
457
+ let i = gid.x;
458
+ if (i >= params.nodeCount) { return; }
459
+ let p = positions[i].xyz;
460
+ let xi = floatToOrderedInt(p.x);
461
+ let yi = floatToOrderedInt(p.y);
462
+ let zi = floatToOrderedInt(p.z);
463
+ atomicMin(&bounds[0], xi); atomicMax(&bounds[1], xi);
464
+ atomicMin(&bounds[2], yi); atomicMax(&bounds[3], yi);
465
+ atomicMin(&bounds[4], zi); atomicMax(&bounds[5], zi);
466
+ }
467
+ `,Ze=`// P2: per-node Morton code from normalized position. Mirrors mortonReference.ts exactly.
468
+
469
+ struct MortonParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
470
+
471
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
472
+ @group(0) @binding(1) var<storage, read> bounds: array<i32, 6>; // result of P1
473
+ @group(0) @binding(2) var<storage, read_write> mortons: array<u32>;
474
+ @group(0) @binding(3) var<storage, read_write> sortedIndices: array<u32>;
475
+ @group(0) @binding(4) var<uniform> params: MortonParams;
476
+
477
+ fn orderedIntToFloat(i: i32) -> f32 {
478
+ return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
479
+ }
480
+
481
+ fn mortonExpand10(v: u32) -> u32 {
482
+ var x = v & 0x3FFu;
483
+ x = (x | (x << 16u)) & 0x030000FFu;
484
+ x = (x | (x << 8u)) & 0x0300F00Fu;
485
+ x = (x | (x << 4u)) & 0x030C30C3u;
486
+ x = (x | (x << 2u)) & 0x09249249u;
487
+ return x;
488
+ }
489
+
490
+ @compute @workgroup_size(64)
491
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
492
+ let i = gid.x;
493
+ if (i >= params.nodeCount) { return; }
494
+
495
+ let minX = orderedIntToFloat(bounds[0]); let maxX = orderedIntToFloat(bounds[1]);
496
+ let minY = orderedIntToFloat(bounds[2]); let maxY = orderedIntToFloat(bounds[3]);
497
+ let minZ = orderedIntToFloat(bounds[4]); let maxZ = orderedIntToFloat(bounds[5]);
498
+ let span = vec3<f32>(max(maxX - minX, 1e-9), max(maxY - minY, 1e-9), max(maxZ - minZ, 1e-9));
499
+
500
+ let p = positions[i].xyz;
501
+ let n01 = (p - vec3<f32>(minX, minY, minZ)) / span; // [0,1]
502
+ let scaled = clamp(n01 * 1024.0, vec3<f32>(0.0), vec3<f32>(1023.0));
503
+ let xi = u32(scaled.x); let yi = u32(scaled.y); let zi = u32(scaled.z);
504
+
505
+ mortons[i] = mortonExpand10(xi) | (mortonExpand10(yi) << 1u) | (mortonExpand10(zi) << 2u);
506
+ sortedIndices[i] = i;
507
+ }
508
+ `,He=`// P4: Karras-2012 binary radix tree build. One thread per internal node (N-1 threads).
509
+ // Each internal node i covers a range of sorted Morton codes; the split is the largest
510
+ // prefix-difference inside the range.
511
+ //
512
+ // Child pointer encoding (consistent with comBuffer layout):
513
+ // child < N-1 \u2192 internal node, comBuffer index = child
514
+ // child >= N-1 \u2192 leaf, comBuffer index = child, leaf_index_in_sorted = child - (N-1)
515
+ //
516
+ // Race-avoidance: each thread writes its OWN slot in \`internalBuf\` (left, right, _, last)
517
+ // AND writes parents of its children into a SEPARATE \`parentBuf\`. Each parentBuf slot is
518
+ // written by exactly one thread (the parent \u2014 child\u2192parent is unique), no race.
519
+
520
+ struct BuildParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
521
+
522
+ @group(0) @binding(0) var<storage, read> mortons: array<u32>;
523
+ @group(0) @binding(1) var<storage, read_write> internalBuf: array<vec4<i32>>; // (left, right, _unused, last)
524
+ @group(0) @binding(2) var<storage, read_write> parentBuf: array<i32>; // pre-initialized to -1 by orchestrator
525
+ @group(0) @binding(3) var<storage, read_write> aabb: array<vec4<f32>>; // 2*(2N-1): [2i]=min, [2i+1]=max
526
+ @group(0) @binding(4) var<storage, read> sortedIndices: array<u32>;
527
+ @group(0) @binding(5) var<storage, read> positions: array<vec4<f32>>;
528
+ @group(0) @binding(6) var<uniform> params: BuildParams;
529
+
530
+ fn lcp(a: i32, b: i32) -> i32 {
531
+ let n = i32(params.nodeCount);
532
+ if (a < 0 || b < 0 || a >= n || b >= n) { return -1; }
533
+ let ua = u32(a); let ub = u32(b);
534
+ if (mortons[ua] == mortons[ub]) {
535
+ // Tie-break with the index itself to ensure unique ordering when Morton codes collide.
536
+ return 32 + i32(countLeadingZeros(ua ^ ub));
537
+ }
538
+ return i32(countLeadingZeros(mortons[ua] ^ mortons[ub]));
539
+ }
540
+
541
+ @compute @workgroup_size(64)
542
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
543
+ let i = i32(gid.x);
544
+ let n = i32(params.nodeCount);
545
+ let internalCount = n - 1;
546
+
547
+ // Initialize leaf AABBs (one thread per leaf \u2014 reusing internal-node thread pool).
548
+ // Each thread also initializes its own leaf entry to keep this self-contained.
549
+ if (i < n) {
550
+ let p = positions[sortedIndices[u32(i)]].xyz;
551
+ let leafBase = (n - 1) + i;
552
+ aabb[2 * leafBase ] = vec4<f32>(p, 0.0);
553
+ aabb[2 * leafBase + 1] = vec4<f32>(p, 0.0);
554
+ }
555
+
556
+ if (i >= internalCount) { return; }
557
+
558
+ // Determine direction d of the range covered by internal node i.
559
+ let lcpRight = lcp(i, i + 1);
560
+ let lcpLeft = lcp(i, i - 1);
561
+ let d = select(-1, 1, lcpRight > lcpLeft);
562
+ let lcpMin = select(lcpRight, lcpLeft, d == 1); // LCP with the "opposite" direction
563
+
564
+ // Exponential search for upper bound of range length.
565
+ var lmax: i32 = 2;
566
+ while (lcp(i, i + lmax * d) > lcpMin) { lmax = lmax * 2; }
567
+
568
+ // Binary search for exact range length l.
569
+ var l: i32 = 0;
570
+ var t: i32 = lmax / 2;
571
+ while (t > 0) {
572
+ if (lcp(i, i + (l + t) * d) > lcpMin) { l = l + t; }
573
+ t = t / 2;
574
+ }
575
+ let j: i32 = i + l * d;
576
+ let first = min(i, j);
577
+ let last = max(i, j);
578
+
579
+ // Find split \u03B3: binary search for the largest position where \u03B4(first, \u03B3) > \u03B4(first, last).
580
+ let lcpNode = lcp(first, last);
581
+ var s: i32 = 0;
582
+ var divisor: i32 = 2;
583
+ var step: i32 = (l + divisor - 1) / divisor; // ceil
584
+ while (step >= 1) {
585
+ if (lcp(i, i + (s + step) * d) > lcpNode) { s = s + step; }
586
+ if (step == 1) { break; }
587
+ divisor = divisor * 2;
588
+ step = (l + divisor - 1) / divisor;
589
+ }
590
+ let gamma: i32 = i + s * d + min(d, 0); // gamma is split point in [first, last)
591
+
592
+ // Encode children: leaf if range collapses to a single element, else internal.
593
+ let leftIsLeaf = (min(i, j) == gamma);
594
+ let rightIsLeaf = (max(i, j) == gamma + 1);
595
+ let leftChild = select(gamma, gamma + (n - 1), leftIsLeaf);
596
+ let rightChild = select(gamma + 1, gamma + 1 + (n - 1), rightIsLeaf);
597
+
598
+ // Write own slot ONLY (no race; each thread owns its index).
599
+ internalBuf[i] = vec4<i32>(leftChild, rightChild, 0, last);
600
+
601
+ // Write parent of each INTERNAL child into parentBuf (leaves don't need parent
602
+ // because depth/COM reduce walks parent\u2192child only). Each parentBuf slot is
603
+ // written by exactly one thread (the unique parent), so no race.
604
+ if (!leftIsLeaf) { parentBuf[leftChild] = i; }
605
+ if (!rightIsLeaf) { parentBuf[rightChild] = i; }
606
+ }
607
+ `,Ve=`// P4b: find the root internal node. The root is the unique internal node with
608
+ // parentBuf[i] == -1 (parentBuf is pre-initialized to -1 by orchestrator; P4 overwrote
609
+ // it for every child of every internal node, so only the root remains at -1).
610
+
611
+ struct FindRootParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
612
+
613
+ @group(0) @binding(0) var<storage, read> parentBuf: array<i32>;
614
+ @group(0) @binding(1) var<storage, read_write> rootOut: array<u32, 1>;
615
+ @group(0) @binding(2) var<uniform> params: FindRootParams;
616
+
617
+ @compute @workgroup_size(64)
618
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
619
+ let i = i32(gid.x);
620
+ let internalCount = i32(params.nodeCount) - 1;
621
+ if (i >= internalCount) { return; }
622
+
623
+ // Exactly one internal node has parent == -1: the root. Safe plain store.
624
+ if (parentBuf[i] == -1) {
625
+ rootOut[0] = u32(i);
626
+ }
627
+ }
628
+ `,Ke=`// P5: BFS ping-pong. One dispatch per BFS level (LBVH_MAX_DEPTH total = 32, empty levels are no-ops).
629
+ // FrontierCount comes from a GPU-side counter buffer (no CPU readback). currentDepth
630
+ // is the only per-dispatch param and uses a DEDICATED per-dispatch uniform buffer
631
+ // (one of LBVH_MAX_DEPTH=32, allocated once in orchestrator init).
632
+
633
+ struct DepthsParams {
634
+ nodeCount: u32,
635
+ currentDepth: u32,
636
+ _pad0: u32,
637
+ _pad1: u32,
638
+ };
639
+
640
+ @group(0) @binding(0) var<storage, read> internalBuf: array<vec4<i32>>;
641
+ @group(0) @binding(1) var<storage, read> queueIn: array<u32>;
642
+ @group(0) @binding(2) var<storage, read_write> queueOut: array<u32>;
643
+ @group(0) @binding(3) var<storage, read_write> frontierCounts: array<atomic<u32>>; // indexed by depth (0..MAX_DEPTH)
644
+ @group(0) @binding(4) var<storage, read_write> depthBuffer: array<u32>;
645
+ @group(0) @binding(5) var<uniform> params: DepthsParams;
646
+
647
+ @compute @workgroup_size(64)
648
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
649
+ let i = gid.x;
650
+ // Read the TRUE frontier size for this depth from the counter buffer.
651
+ // atomicLoad is the correct read primitive for an atomic<u32>.
652
+ let frontierCount = atomicLoad(&frontierCounts[params.currentDepth]);
653
+ if (i >= frontierCount) { return; }
654
+
655
+ let nodeIdx = queueIn[i]; // internal node index (u32)
656
+ depthBuffer[nodeIdx] = params.currentDepth;
657
+
658
+ let entry = internalBuf[nodeIdx];
659
+ let leftChild = entry.x; // i32
660
+ let rightChild = entry.y;
661
+ let internalCount = i32(params.nodeCount) - 1;
662
+
663
+ // Enqueue only INTERNAL children (leaves don't need depth).
664
+ if (leftChild < internalCount) {
665
+ let slot = atomicAdd(&frontierCounts[params.currentDepth + 1u], 1u);
666
+ queueOut[slot] = u32(leftChild);
667
+ }
668
+ if (rightChild < internalCount) {
669
+ let slot = atomicAdd(&frontierCounts[params.currentDepth + 1u], 1u);
670
+ queueOut[slot] = u32(rightChild);
671
+ }
672
+ }
673
+ `,$e=`// P6: COM and AABB reduce.
674
+ // Two entry points, selected by pipeline at dispatch time:
675
+ // leafInit: initialize comBuffer[N-1..2N-2] from leaf positions.
676
+ // levelReduce: for each internal node at depthBuffer[i] == currentLevel, combine
677
+ // child COMs/AABBs into comBuffer[nodeIdx] and aabbBuffer[2i..2i+1].
678
+
679
+ struct ReduceParams {
680
+ nodeCount: u32,
681
+ currentLevel: u32,
682
+ _pad0: u32,
683
+ _pad1: u32,
684
+ };
685
+
686
+ @group(0) @binding(0) var<storage, read> internalBuf: array<vec4<i32>>;
687
+ @group(0) @binding(1) var<storage, read_write> comBuffer: array<vec4<f32>>; // (x, y, z, mass), 2N-1 entries
688
+ @group(0) @binding(2) var<storage, read_write> aabbBuffer: array<vec4<f32>>; // 2*(2N-1) entries (min, max alternating)
689
+ @group(0) @binding(3) var<storage, read> depthBuffer: array<u32>;
690
+ @group(0) @binding(4) var<storage, read> sortedIndices: array<u32>;
691
+ @group(0) @binding(5) var<storage, read> positions: array<vec4<f32>>;
692
+ @group(0) @binding(6) var<uniform> params: ReduceParams;
693
+
694
+ @compute @workgroup_size(64)
695
+ fn leafInit(@builtin(global_invocation_id) gid: vec3<u32>) {
696
+ let i = gid.x;
697
+ if (i >= params.nodeCount) { return; }
698
+ let leafIdxInCom = (params.nodeCount - 1u) + i; // comBuffer layout: leaves at [N-1, 2N-2]
699
+ let p = positions[sortedIndices[i]].xyz;
700
+ comBuffer[leafIdxInCom] = vec4<f32>(p, 1.0);
701
+ // aabb already initialized by P4 leaf-init step
702
+ }
703
+
704
+ @compute @workgroup_size(64)
705
+ fn levelReduce(@builtin(global_invocation_id) gid: vec3<u32>) {
706
+ let i = gid.x;
707
+ let internalCount = params.nodeCount - 1u;
708
+ if (i >= internalCount) { return; }
709
+ if (depthBuffer[i] != params.currentLevel) { return; }
710
+
711
+ let entry = internalBuf[i];
712
+ let leftChild = u32(entry.x);
713
+ let rightChild = u32(entry.y);
714
+
715
+ // Both children's COMs and AABBs are already in their buffer slots
716
+ // (set either by leafInit or a deeper-level reduce dispatch).
717
+ let cL = comBuffer[leftChild];
718
+ let cR = comBuffer[rightChild];
719
+ let totalMass = cL.w + cR.w;
720
+ let com = vec4<f32>((cL.xyz * cL.w + cR.xyz * cR.w) / totalMass, totalMass);
721
+ comBuffer[i] = com;
722
+
723
+ let aabbMinL = aabbBuffer[2u * leftChild].xyz;
724
+ let aabbMaxL = aabbBuffer[2u * leftChild + 1u].xyz;
725
+ let aabbMinR = aabbBuffer[2u * rightChild].xyz;
726
+ let aabbMaxR = aabbBuffer[2u * rightChild + 1u].xyz;
727
+ aabbBuffer[2u * i] = vec4<f32>(min(aabbMinL, aabbMinR), 0.0);
728
+ aabbBuffer[2u * i + 1u] = vec4<f32>(max(aabbMaxL, aabbMaxR), 0.0);
729
+ }
730
+ `,Qe=`// P7: per-query-node DFS traversal with Barnes-Hut criterion. One thread per node.
731
+ // Writes accumulated velocity directly to velocities[i].xyz (no atomics needed \u2014
732
+ // each thread owns its own output slot). Self-interaction guard skips the query
733
+ // node's own entry in leaf cells.
734
+
735
+ struct TraverseParams {
736
+ nodeCount: u32,
737
+ strength: f32,
738
+ alpha: f32,
739
+ theta2: f32, // \u03B8\xB2 for fast Barnes-Hut compare
740
+ distanceMin2: f32, // d3-force-3d distanceMin\xB2 clamp; matches close-range damping
741
+ distanceMax2: f32, // d3-force-3d distanceMax\xB2 cutoff; forces beyond this distance are ignored
742
+ _pad1: f32,
743
+ _pad2: f32,
744
+ };
745
+
746
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
747
+ @group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
748
+ @group(0) @binding(2) var<storage, read> internalBuf: array<vec4<i32>>;
749
+ @group(0) @binding(3) var<storage, read> comBuffer: array<vec4<f32>>;
750
+ @group(0) @binding(4) var<storage, read> aabbBuffer: array<vec4<f32>>;
751
+ @group(0) @binding(5) var<storage, read> sortedIndices: array<u32>;
752
+ @group(0) @binding(6) var<storage, read> rootBuf: array<u32, 1>;
753
+ @group(0) @binding(7) var<uniform> params: TraverseParams;
754
+
755
+ // MAX_DEPTH MUST equal LBVH_MAX_DEPTH from constants.ts (currently 32).
756
+ // Workgroup memory: 64 \xD7 32 \xD7 4 = 8192 bytes (well under 16384-byte default limit).
757
+ const WG_SIZE: u32 = 64u;
758
+ const MAX_DEPTH: u32 = 32u;
759
+ var<workgroup> stack: array<u32, WG_SIZE * MAX_DEPTH>;
760
+
761
+ // d3-force-3d distanceMin clamp: if l < dmin\xB2, l := sqrt(dmin\xB2 \xD7 l).
762
+ // Converts the 1/r\xB2 singularity at close range into 1/r (linear), preventing
763
+ // the close-range "explosion" that produces spiky/streaky layouts.
764
+ fn clampDistance(l: f32) -> f32 {
765
+ return select(l, sqrt(params.distanceMin2 * l), l < params.distanceMin2);
766
+ }
767
+
768
+ @compute @workgroup_size(64)
769
+ fn main(
770
+ @builtin(global_invocation_id) gid: vec3<u32>,
771
+ @builtin(local_invocation_index) lid: u32,
772
+ ) {
773
+ let queryIdx = gid.x;
774
+ if (queryIdx >= params.nodeCount) { return; }
775
+
776
+ // queryIdx is an ORIGINAL node index (one thread per original node).
777
+ let queryPos = positions[queryIdx].xyz;
778
+ var accum = vec3<f32>(0.0, 0.0, 0.0);
779
+
780
+ // DFS init: stack starts with root.
781
+ var stackTop: u32 = 0u;
782
+ let stackBase = lid * MAX_DEPTH;
783
+ stack[stackBase + stackTop] = rootBuf[0];
784
+ stackTop = stackTop + 1u;
785
+
786
+ let internalCount: u32 = params.nodeCount - 1u;
787
+
788
+ loop {
789
+ if (stackTop == 0u) { break; }
790
+ stackTop = stackTop - 1u;
791
+ let node = stack[stackBase + stackTop];
792
+
793
+ // Barnes-Hut criterion: max axis extent\xB2 vs \u03B8\xB2 \xD7 d\xB2 (matches d3-force-3d's
794
+ // cubic-cell \`w\xB2 < l \xD7 \u03B8\xB2\`, where w is the cell edge length).
795
+ let aMin = aabbBuffer[2u * node].xyz;
796
+ let aMax = aabbBuffer[2u * node + 1u].xyz;
797
+ let com = comBuffer[node];
798
+ let diff = com.xyz - queryPos;
799
+ let d2_raw = max(dot(diff, diff), 1e-12);
800
+ let sizeVec = aMax - aMin;
801
+ let maxEdge = max(sizeVec.x, max(sizeVec.y, sizeVec.z));
802
+ let s2 = maxEdge * maxEdge;
803
+
804
+ if (s2 <= params.theta2 * d2_raw) {
805
+ // Far enough: approximate cluster by COM with d3-distanceMin clamp.
806
+ let l = clampDistance(d2_raw);
807
+ if (l >= params.distanceMax2) { continue; }
808
+ let c = params.strength * params.alpha * com.w / l;
809
+ accum = accum + diff * c;
810
+ continue;
811
+ }
812
+
813
+ if (node < internalCount) {
814
+ // Internal: descend into both children.
815
+ let entry = internalBuf[node];
816
+ let leftChild = u32(entry.x);
817
+ let rightChild = u32(entry.y);
818
+ if (stackTop < MAX_DEPTH - 1u) {
819
+ stack[stackBase + stackTop] = leftChild; stackTop = stackTop + 1u;
820
+ stack[stackBase + stackTop] = rightChild; stackTop = stackTop + 1u;
821
+ }
822
+ continue;
823
+ }
824
+
825
+ // Leaf: a single original node. Self-interaction guard.
826
+ let leafIdx = node - internalCount; // leaf rank in sortedIndices
827
+ let neighborIdx = sortedIndices[leafIdx];
828
+ if (neighborIdx == queryIdx) { continue; }
829
+ let np = positions[neighborIdx].xyz;
830
+ let nd = np - queryPos;
831
+ let nd2_raw = max(dot(nd, nd), 1e-12);
832
+ let nl = clampDistance(nd2_raw);
833
+ if (nl >= params.distanceMax2) { continue; }
834
+ let nc = params.strength * params.alpha / nl; // unit mass
835
+ accum = accum + nd * nc;
836
+ }
837
+
838
+ velocities[queryIdx] = vec4<f32>(velocities[queryIdx].xyz + accum, velocities[queryIdx].w);
839
+ }
840
+ `,Je=`// P3: one bitonic compare-swap step. Dispatched once per (k, j) in bitonicSortSteps().
841
+
842
+ struct SortParams { n: u32, k: u32, j: u32, _pad: u32 };
843
+
844
+ @group(0) @binding(0) var<storage, read_write> keys: array<u32>;
845
+ @group(0) @binding(1) var<storage, read_write> values: array<u32>;
846
+ @group(0) @binding(2) var<uniform> params: SortParams;
847
+
848
+ @compute @workgroup_size(64)
849
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
850
+ let i = gid.x;
851
+ if (i >= params.n) { return; }
852
+ let partner = i ^ params.j;
853
+ if (partner <= i) { return; }
854
+ if (partner >= params.n) { return; }
855
+
856
+ let ascending = (i & params.k) == 0u;
857
+ let kI = keys[i];
858
+ let kP = keys[partner];
859
+ // Parens required: bare \`kI < kP, kI > kP\` triggers WGSL template-list parsing.
860
+ let swap = select((kI < kP), (kI > kP), ascending);
861
+ if (swap) {
862
+ keys[i] = kP;
863
+ keys[partner] = kI;
864
+ let vI = values[i];
865
+ values[i] = values[partner];
866
+ values[partner] = vI;
867
+ }
868
+ }
869
+ `;function en(e){let n=[];for(let r=2;r<=e;r*=2)for(let t=r/2;t>0;t=t>>1)n.push({k:r,j:t});return n}var nn=16,tn=class{constructor(e){this.device=e,this.paramsBuffers=[];let n=e.createShaderModule({label:"lbvh-sort",code:Je});this.pipeline=e.createComputePipeline({label:"lbvh-sort-pipeline",layout:"auto",compute:{module:n,entryPoint:"main"}})}ensureParamsBuffer(e){for(;this.paramsBuffers.length<=e;)this.paramsBuffers.push(this.device.createBuffer({label:`lbvh-sort-params-${this.paramsBuffers.length}`,size:nn,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));return this.paramsBuffers[e]}sort(e,n,r,t){let i=en(t);for(let a=0;a<i.length;a++){let{k:s,j:o}=i[a],u=this.ensureParamsBuffer(a);this.device.queue.writeBuffer(u,0,new Uint32Array([t,s,o,0]));let l=this.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n}},{binding:1,resource:{buffer:r}},{binding:2,resource:{buffer:u}}]}),m=e.beginComputePass({label:`bitonic k=${s} j=${o}`});m.setPipeline(this.pipeline),m.setBindGroup(0,l),m.dispatchWorkgroups(Math.ceil(t/fe)),m.end()}}dispose(){for(let e of this.paramsBuffers)e.destroy();this.paramsBuffers=[]}},rn=class{constructor(e,n){this.ctx=e,this.buffers=n,this.depthsParamsBufs=[],this.reduceParamsBufs=[],this.depthsBG_AtoB=[],this.depthsBG_BtoA=[],this.reduceLevelBGs=[],this.nodeCount=0,this.theta=.9,this.strength=-30,this.distanceMin=1,this.distanceMax=1/0,this.nodeCount=e.nodeCount,this.init()}setTheta(e){this.theta=e}setStrength(e){this.strength=e}setDistanceMin(e){this.distanceMin=e}setDistanceMax(e){this.distanceMax=e}init(){let e=this.ctx.device,n=(a,s=16)=>e.createBuffer({label:a,size:s,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.boundsParamsBuf=n("lbvh-bounds-params"),this.mortonParamsBuf=n("lbvh-morton-params"),this.buildParamsBuf=n("lbvh-build-params"),this.findRootParamsBuf=n("lbvh-find-root-params"),this.traverseParamsBuf=n("lbvh-traverse-params",32);for(let a=0;a<R;a++){let s=n(`lbvh-depths-params-${a}`);e.queue.writeBuffer(s,0,new Uint32Array([this.nodeCount,a,0,0])),this.depthsParamsBufs.push(s)}for(let a=0;a<=R;a++){let s=n(`lbvh-reduce-params-${a}`);e.queue.writeBuffer(s,0,new Uint32Array([this.nodeCount,a===0?0:a-1,0,0])),this.reduceParamsBufs.push(s)}let r=(a,s)=>e.createShaderModule({label:a,code:s}),t=(a,s,o)=>e.createComputePipeline({label:a,layout:"auto",compute:{module:s,entryPoint:o}});this.boundsPipeline=t("lbvh-bounds",r("lbvh-bounds",se),"main"),this.mortonPipeline=t("lbvh-morton",r("lbvh-morton",Ze),"main"),this.buildPipeline=t("lbvh-build",r("lbvh-build",He),"main"),this.findRootPipeline=t("lbvh-find-root",r("lbvh-find-root",Ve),"main"),this.depthsPipeline=t("lbvh-depths",r("lbvh-depths",Ke),"main");let i=r("lbvh-reduce",$e);this.reduceLeafInitPipeline=t("lbvh-reduce-leafInit",i,"leafInit"),this.reduceLevelPipeline=t("lbvh-reduce-level",i,"levelReduce"),this.traversePipeline=t("lbvh-traverse",r("lbvh-traverse",Qe),"main"),this.sortPass=new tn(e),this.bindAll()}bindAll(){let e=this.ctx.device,n=this.buffers,r=this.ctx;this.boundsBG=e.createBindGroup({layout:this.boundsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:r.positions}},{binding:1,resource:{buffer:n.bounds}},{binding:2,resource:{buffer:this.boundsParamsBuf}}]}),this.mortonBG=e.createBindGroup({layout:this.mortonPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:r.positions}},{binding:1,resource:{buffer:n.bounds}},{binding:2,resource:{buffer:n.morton}},{binding:3,resource:{buffer:n.sortedIndices}},{binding:4,resource:{buffer:this.mortonParamsBuf}}]}),this.buildBG=e.createBindGroup({layout:this.buildPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.morton}},{binding:1,resource:{buffer:n.internal}},{binding:2,resource:{buffer:n.parent}},{binding:3,resource:{buffer:n.aabb}},{binding:4,resource:{buffer:n.sortedIndices}},{binding:5,resource:{buffer:r.positions}},{binding:6,resource:{buffer:this.buildParamsBuf}}]}),this.findRootBG=e.createBindGroup({layout:this.findRootPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.parent}},{binding:1,resource:{buffer:n.root}},{binding:2,resource:{buffer:this.findRootParamsBuf}}]});for(let t=0;t<R;t++)this.depthsBG_AtoB.push(e.createBindGroup({layout:this.depthsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.internal}},{binding:1,resource:{buffer:n.depthQueueA}},{binding:2,resource:{buffer:n.depthQueueB}},{binding:3,resource:{buffer:n.frontierCounts}},{binding:4,resource:{buffer:n.depth}},{binding:5,resource:{buffer:this.depthsParamsBufs[t]}}]})),this.depthsBG_BtoA.push(e.createBindGroup({layout:this.depthsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.internal}},{binding:1,resource:{buffer:n.depthQueueB}},{binding:2,resource:{buffer:n.depthQueueA}},{binding:3,resource:{buffer:n.frontierCounts}},{binding:4,resource:{buffer:n.depth}},{binding:5,resource:{buffer:this.depthsParamsBufs[t]}}]}));this.reduceLeafInitBG=e.createBindGroup({layout:this.reduceLeafInitPipeline.getBindGroupLayout(0),entries:[{binding:1,resource:{buffer:n.com}},{binding:4,resource:{buffer:n.sortedIndices}},{binding:5,resource:{buffer:r.positions}},{binding:6,resource:{buffer:this.reduceParamsBufs[0]}}]});for(let t=0;t<R;t++)this.reduceLevelBGs.push(e.createBindGroup({layout:this.reduceLevelPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.internal}},{binding:1,resource:{buffer:n.com}},{binding:2,resource:{buffer:n.aabb}},{binding:3,resource:{buffer:n.depth}},{binding:6,resource:{buffer:this.reduceParamsBufs[t+1]}}]}));this.traverseBG=e.createBindGroup({layout:this.traversePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:r.positions}},{binding:1,resource:{buffer:r.velocities}},{binding:2,resource:{buffer:n.internal}},{binding:3,resource:{buffer:n.com}},{binding:4,resource:{buffer:n.aabb}},{binding:5,resource:{buffer:n.sortedIndices}},{binding:6,resource:{buffer:n.root}},{binding:7,resource:{buffer:this.traverseParamsBuf}}]}),e.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0])),e.queue.writeBuffer(this.mortonParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0])),e.queue.writeBuffer(this.buildParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0])),e.queue.writeBuffer(this.findRootParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]))}apply(e,n){let r=this.ctx.device,t=this.nodeCount;if(t<2)return;let i=fe,a=Math.ceil(t/i),s=Math.ceil(Math.max(1,t-1)/i),o=this.buffers.paddedN,u=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);if(r.queue.writeBuffer(this.buffers.bounds,0,u),o>t){let b=new Uint32Array(o-t).fill(4294967295),P=new Uint32Array(o-t).fill(4294967295);r.queue.writeBuffer(this.buffers.morton,t*4,b),r.queue.writeBuffer(this.buffers.sortedIndices,t*4,P)}let l=new Int32Array(Math.max(1,t-1)).fill(-1);r.queue.writeBuffer(this.buffers.parent,0,l);let m=new Uint32Array(R+1);m[0]=1,r.queue.writeBuffer(this.buffers.frontierCounts,0,m),r.queue.writeBuffer(this.buffers.root,0,new Uint32Array([0]));let h=Number.isFinite(this.distanceMax)?this.distanceMax*this.distanceMax:34e37,d=new ArrayBuffer(32);new Uint32Array(d,0,1)[0]=t,new Float32Array(d,4,5).set([this.strength,e,this.theta*this.theta,this.distanceMin*this.distanceMin,h]),r.queue.writeBuffer(this.traverseParamsBuf,0,d),this.runSimple(n,this.boundsPipeline,this.boundsBG,a,"p1-bounds"),this.runSimple(n,this.mortonPipeline,this.mortonBG,a,"p2-morton"),this.sortPass.sort(n,this.buffers.morton,this.buffers.sortedIndices,o),this.runSimple(n,this.buildPipeline,this.buildBG,Math.max(s,a),"p4-build"),this.runSimple(n,this.findRootPipeline,this.findRootBG,s,"p4b-find-root"),n.copyBufferToBuffer(this.buffers.root,0,this.buffers.depthQueueA,0,4);for(let b=0;b<R;b++){let g=b%2===0?this.depthsBG_AtoB[b]:this.depthsBG_BtoA[b],f=n.beginComputePass({label:`p5-depths-${b}`});f.setPipeline(this.depthsPipeline),f.setBindGroup(0,g),f.dispatchWorkgroups(s),f.end()}this.runSimple(n,this.reduceLeafInitPipeline,this.reduceLeafInitBG,a,"p6-leafInit");for(let b=R-1;b>=0;b--)this.runSimple(n,this.reduceLevelPipeline,this.reduceLevelBGs[b],s,`p6-level-${b}`);this.runSimple(n,this.traversePipeline,this.traverseBG,a,"p7-traverse")}runSimple(e,n,r,t,i){let a=e.beginComputePass({label:i});a.setPipeline(n),a.setBindGroup(0,r),a.dispatchWorkgroups(t),a.end()}dispose(){this.sortPass.dispose();for(let e of[this.boundsParamsBuf,this.mortonParamsBuf,this.buildParamsBuf,this.findRootParamsBuf,this.traverseParamsBuf,...this.depthsParamsBufs,...this.reduceParamsBufs])e.destroy()}};function an(){let e=-30,n=Ye,r=1,t=1/0,i=null,a=null,s={initialize(o,u,l){},initGPU(o){(a||i)&&(a?.dispose(),i?.dispose(),a=null,i=null),i=je(o.device,o.nodeCount,R);let u={device:o.device,nodeCount:o.nodeCount,positions:o.positionBuffer,velocities:o.velocityBuffer};a=new rn(u,i),a.setStrength(e),a.setTheta(n),a.setDistanceMin(r),a.setDistanceMax(t)},apply(o,u){a?.apply(o,u)},dispose(){a?.dispose(),i?.dispose(),a=null,i=null},strength(o){return arguments.length===0?e:(e=+o,a?.setStrength(e),s)},theta(o){return arguments.length===0?n:(n=+o,a?.setTheta(n),s)},distanceMin(o){return arguments.length===0?r:(r=+o,a?.setDistanceMin(r),s)},distanceMax(o){return arguments.length===0?t:(t=+o,a?.setDistanceMax(t),s)}};return s}var pe=`// Clear quadtree cell buffer to zero. One thread per cell slot (4 i32s/cell).
870
+ //
871
+ // Layout:
872
+ // group(0)
873
+ // binding(0) cells array<atomic<i32>> read_write
874
+ // binding(1) params ClearParams uniform
875
+
876
+ struct ClearParams {
877
+ cellSlotCount: u32, // totalCells \xD7 CELL_STRIDE (4)
878
+ // Number of invocations per Y-row of the dispatch grid (= workgroupCountX \xD7 workgroup_size).
879
+ // Used to recover the linear slot index from a 2D dispatch. Required because the
880
+ // 3D octree at L=7 needs ~150k workgroups for clear, exceeding WebGPU's 65,535
881
+ // per-dim limit; we split across X and Y instead.
882
+ dispatchStrideX: u32,
883
+ _pad1: u32,
884
+ _pad2: u32,
885
+ };
886
+
887
+ @group(0) @binding(0) var<storage, read_write> cells: array<atomic<i32>>;
888
+ @group(0) @binding(1) var<uniform> params: ClearParams;
889
+
890
+ @compute @workgroup_size(64)
891
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
892
+ let i = gid.y * params.dispatchStrideX + gid.x;
893
+ if (i >= params.cellSlotCount) { return; }
894
+ atomicStore(&cells[i], 0);
895
+ }
896
+ `,sn=`// quad-bin: per-node atomic write of (x, y, mass) into the LEAF cell at MAX level
897
+ // of a fixed-depth 2D quadtree. Reads bounds directly from boundsBuffer (ordered-int
898
+ // encoding produced by lbvh-bounds.wgsl).
899
+ //
900
+ // Cells indexed by Morton interleave (cellX, cellY).
901
+ // leafOffset = (4^L - 1) / 3
902
+ // mortonIdx = interleave(cellX, cellY) in [0, 4^L)
903
+ // Fixed-point sums: position * FIXED_SCALE as i32 atomicAdd. Mass = 1 (count).
904
+
905
+ struct BinParams {
906
+ nodeCount: u32,
907
+ maxLevel: u32,
908
+ leafOffset: u32,
909
+ fixedScale: f32,
910
+ };
911
+
912
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
913
+ @group(0) @binding(1) var<storage, read_write> cells: array<atomic<i32>>;
914
+ @group(0) @binding(2) var<storage, read> bounds: array<i32, 6>; // xMin,xMax,yMin,yMax,zMin,zMax (ordered-int)
915
+ @group(0) @binding(3) var<uniform> params: BinParams;
916
+
917
+ fn orderedIntToFloat(i: i32) -> f32 {
918
+ return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
919
+ }
920
+
921
+ fn mortonExpand16(v: u32) -> u32 {
922
+ var x = v & 0xFFFFu;
923
+ x = (x | (x << 8u)) & 0x00FF00FFu;
924
+ x = (x | (x << 4u)) & 0x0F0F0F0Fu;
925
+ x = (x | (x << 2u)) & 0x33333333u;
926
+ x = (x | (x << 1u)) & 0x55555555u;
927
+ return x;
928
+ }
929
+
930
+ @compute @workgroup_size(64)
931
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
932
+ let i = gid.x;
933
+ if (i >= params.nodeCount) { return; }
934
+
935
+ let xMin = orderedIntToFloat(bounds[0]);
936
+ let xMax = orderedIntToFloat(bounds[1]);
937
+ let yMin = orderedIntToFloat(bounds[2]);
938
+ let yMax = orderedIntToFloat(bounds[3]);
939
+ let spanX = max(xMax - xMin, 1e-9);
940
+ let spanY = max(yMax - yMin, 1e-9);
941
+
942
+ let p = positions[i].xy;
943
+ let levelSize = 1u << params.maxLevel;
944
+ let n01 = clamp(vec2<f32>((p.x - xMin) / spanX, (p.y - yMin) / spanY),
945
+ vec2<f32>(0.0), vec2<f32>(0.999999));
946
+ let cellXi = u32(n01.x * f32(levelSize));
947
+ let cellYi = u32(n01.y * f32(levelSize));
948
+ let mortonIdx = mortonExpand16(cellXi) | (mortonExpand16(cellYi) << 1u);
949
+
950
+ let cellArrayIdx = params.leafOffset + mortonIdx;
951
+ let baseSlot = cellArrayIdx * 4u;
952
+
953
+ // Store raw \`p * fixedScale\` (legacy semantics). FIXED_SCALE chosen small
954
+ // enough that N \xD7 max|p| \xD7 scale < 2^31 (no i32 overflow at typical scales).
955
+ // Normalized variant tested 2026-05-21 \u2014 math was correct but produced 3\xD7
956
+ // wider layout than legacy at same params; reverted to raw.
957
+ let xFixed = i32(p.x * params.fixedScale);
958
+ let yFixed = i32(p.y * params.fixedScale);
959
+ atomicAdd(&cells[baseSlot + 0u], xFixed);
960
+ atomicAdd(&cells[baseSlot + 1u], yFixed);
961
+ atomicAdd(&cells[baseSlot + 3u], 1i);
962
+ }
963
+ `,on=`// quad-accumulate: bottom-up COM aggregation.
964
+ //
965
+ // Dispatched once per level k (from MAX_LEVEL-1 down to 0). For each cell at
966
+ // level k (4^k cells), read its 4 children at level k+1 (Morton-contiguous:
967
+ // children of cell M are M*4, M*4+1, M*4+2, M*4+3), sum their (sum_x, sum_y,
968
+ // mass), write to parent slot.
969
+ //
970
+ // d3-force-3d's accumulate(): treeNode.x = \u03A3(child.x * child.mass) / \u03A3mass.
971
+ // We store (sum_x, sum_y, mass) directly (no division yet) \u2014 traverse divides
972
+ // at read time. Avoids precision loss from premature division.
973
+
974
+ struct AccumParams {
975
+ parentOffset: u32, // (4^k - 1) / 3 \u2014 offset of level k cells
976
+ childOffset: u32, // (4^(k+1) - 1) / 3 \u2014 offset of level k+1 cells
977
+ parentCount: u32, // 4^k \u2014 number of cells at parent level
978
+ _pad: u32,
979
+ };
980
+
981
+ @group(0) @binding(0) var<storage, read_write> cells: array<atomic<i32>>;
982
+ @group(0) @binding(1) var<uniform> params: AccumParams;
983
+
984
+ @compute @workgroup_size(64)
985
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
986
+ let pi = gid.x;
987
+ if (pi >= params.parentCount) { return; }
988
+
989
+ let parentBase = (params.parentOffset + pi) * 4u;
990
+ let child0Base = (params.childOffset + pi * 4u) * 4u;
991
+
992
+ var sx: i32 = 0;
993
+ var sy: i32 = 0;
994
+ var sm: i32 = 0;
995
+ for (var c: u32 = 0u; c < 4u; c = c + 1u) {
996
+ let cb = child0Base + c * 4u;
997
+ sx = sx + atomicLoad(&cells[cb + 0u]);
998
+ sy = sy + atomicLoad(&cells[cb + 1u]);
999
+ sm = sm + atomicLoad(&cells[cb + 3u]);
1000
+ }
1001
+ atomicStore(&cells[parentBase + 0u], sx);
1002
+ atomicStore(&cells[parentBase + 1u], sy);
1003
+ atomicStore(&cells[parentBase + 3u], sm);
1004
+ }
1005
+ `,un=`// quad-traverse: per-query-node Barnes-Hut DFS over a fixed-depth 2D quadtree.
1006
+ // Matches d3-force-3d's apply() (manyBody.js).
1007
+ //
1008
+ // Reads bounds directly from boundsBuffer to compute cellWidth at each level.
1009
+ // 2D only \u2014 z component of position/velocity untouched.
1010
+
1011
+ struct TraverseParams {
1012
+ nodeCount: u32,
1013
+ maxLevel: u32,
1014
+ _pad0: u32,
1015
+ _pad1: u32,
1016
+ strength: f32,
1017
+ alpha: f32,
1018
+ theta2: f32,
1019
+ distanceMin2: f32,
1020
+ distanceMax2: f32,
1021
+ fixedScale: f32,
1022
+ _pad2: f32,
1023
+ _pad3: f32,
1024
+ };
1025
+
1026
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
1027
+ @group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
1028
+ // atomic variables MUST be read_write in WGSL (even when only atomicLoad-ed).
1029
+ @group(0) @binding(2) var<storage, read_write> cells: array<atomic<i32>>;
1030
+ @group(0) @binding(3) var<storage, read> levelOffsets: array<u32>;
1031
+ @group(0) @binding(4) var<storage, read> bounds: array<i32, 6>;
1032
+ @group(0) @binding(5) var<uniform> params: TraverseParams;
1033
+
1034
+ fn orderedIntToFloat(i: i32) -> f32 {
1035
+ return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
1036
+ }
1037
+
1038
+ // 16-bit value \u2192 32-bit interleaved (kept in sync with quad-bin.wgsl). Used to
1039
+ // compute the query's own leaf cellIdx so the leaf-level branch can subtract
1040
+ // the query's contribution from the cell COM (leaf-COM fix; see
1041
+ // oct-traverse.wgsl for the 3D analogue).
1042
+ fn mortonExpand16(v: u32) -> u32 {
1043
+ var x = v & 0xFFFFu;
1044
+ x = (x | (x << 8u)) & 0x00FF00FFu;
1045
+ x = (x | (x << 4u)) & 0x0F0F0F0Fu;
1046
+ x = (x | (x << 2u)) & 0x33333333u;
1047
+ x = (x | (x << 1u)) & 0x55555555u;
1048
+ return x;
1049
+ }
1050
+
1051
+ // MAX_STACK=32: max tree depth = 8 levels, each internal pop pushes 4 \u2192 worst-case
1052
+ // stack depth \u2264 4 \xD7 maxLevel = 32. Workgroup memory: 64 \xD7 32 \xD7 4 = 8 KB (limit 16 KB).
1053
+ // Pack (level, cellIdx) into single u32: high 8 bits = level (0..32), low 24 bits =
1054
+ // cellIdx (max 87381 = ((4^9-1)/3) fits in 17 bits, plenty of room in 24).
1055
+ const WG_SIZE: u32 = 64u;
1056
+ const MAX_STACK: u32 = 32u;
1057
+ var<workgroup> stack: array<u32, 2048>; // WG_SIZE \xD7 MAX_STACK
1058
+
1059
+ @compute @workgroup_size(64)
1060
+ fn main(
1061
+ @builtin(global_invocation_id) gid: vec3<u32>,
1062
+ @builtin(local_invocation_index) lid: u32,
1063
+ ) {
1064
+ let queryIdx = gid.x;
1065
+ if (queryIdx >= params.nodeCount) { return; }
1066
+
1067
+ let qp = positions[queryIdx].xy;
1068
+ var accum = vec2<f32>(0.0, 0.0);
1069
+ let stackBase = lid * MAX_STACK;
1070
+ let invScale = 1.0 / params.fixedScale;
1071
+
1072
+ let xMin = orderedIntToFloat(bounds[0]);
1073
+ let xMax = orderedIntToFloat(bounds[1]);
1074
+ let yMin = orderedIntToFloat(bounds[2]);
1075
+ let yMax = orderedIntToFloat(bounds[3]);
1076
+ let boundsMax = max(xMax - xMin, yMax - yMin);
1077
+
1078
+ // Precompute query's own leaf cellIdx (same mapping as quad-bin.wgsl) so the
1079
+ // leaf-level branch can subtract self-contribution and avoid the cross-star.
1080
+ let spanXq = max(xMax - xMin, 1e-9);
1081
+ let spanYq = max(yMax - yMin, 1e-9);
1082
+ let levelSizeMax = 1u << params.maxLevel;
1083
+ let n01q = clamp(
1084
+ vec2<f32>((qp.x - xMin) / spanXq, (qp.y - yMin) / spanYq),
1085
+ vec2<f32>(0.0), vec2<f32>(0.999999));
1086
+ let qcx = u32(n01q.x * f32(levelSizeMax));
1087
+ let qcy = u32(n01q.y * f32(levelSizeMax));
1088
+ let queryMorton = mortonExpand16(qcx) | (mortonExpand16(qcy) << 1u);
1089
+ let queryLeafCellIdx = levelOffsets[params.maxLevel] + queryMorton;
1090
+
1091
+ // Push root: level=0, cellIdx=0. Packed: (0 << 24) | 0 = 0.
1092
+ var top: u32 = 0u;
1093
+ stack[stackBase + top] = 0u;
1094
+ top = top + 1u;
1095
+
1096
+ loop {
1097
+ if (top == 0u) { break; }
1098
+ top = top - 1u;
1099
+ let packed = stack[stackBase + top];
1100
+ let level = packed >> 24u;
1101
+ let cellIdx = packed & 0x00FFFFFFu;
1102
+
1103
+ let cb = cellIdx * 4u;
1104
+ let mass = f32(atomicLoad(&cells[cb + 3u]));
1105
+ if (mass < 0.5) { continue; }
1106
+ let sumX = f32(atomicLoad(&cells[cb + 0u])) * invScale;
1107
+ let sumY = f32(atomicLoad(&cells[cb + 1u])) * invScale;
1108
+ let comX = sumX / mass;
1109
+ let comY = sumY / mass;
1110
+
1111
+ let levelSize = f32(1u << level);
1112
+ let cellWidth = boundsMax / levelSize;
1113
+
1114
+ let dx = comX - qp.x;
1115
+ let dy = comY - qp.y;
1116
+ let l = max(dx * dx + dy * dy, 1e-12);
1117
+
1118
+ // BH criterion: cellWidth\xB2 / \u03B8\xB2 < l \u27FA cellWidth\xB2 < l \xD7 \u03B8\xB2
1119
+ if (cellWidth * cellWidth < l * params.theta2) {
1120
+ var l2 = l;
1121
+ if (l2 >= params.distanceMax2) { continue; }
1122
+ if (l2 < params.distanceMin2) { l2 = sqrt(params.distanceMin2 * l2); }
1123
+ let c = params.strength * mass * params.alpha / l2;
1124
+ accum.x = accum.x + dx * c;
1125
+ accum.y = accum.y + dy * c;
1126
+ continue;
1127
+ }
1128
+
1129
+ if (level >= params.maxLevel) {
1130
+ // Leaf-COM fix: if this leaf is the query's own cell, subtract the
1131
+ // query's (x, y, 1) contribution from the cell sum/count so the effective
1132
+ // COM is the centroid of the OTHER nodes in the leaf. See oct-traverse
1133
+ // for rationale (cross-star avoidance on dense graphs).
1134
+ if (cellIdx == queryLeafCellIdx) {
1135
+ let adjMass = mass - 1.0;
1136
+ if (adjMass < 0.5) { continue; } // query was the sole occupant
1137
+ let adjSumX = sumX - qp.x;
1138
+ let adjSumY = sumY - qp.y;
1139
+ let adjComX = adjSumX / adjMass;
1140
+ let adjComY = adjSumY / adjMass;
1141
+ let dxa = adjComX - qp.x;
1142
+ let dya = adjComY - qp.y;
1143
+ var la = max(dxa * dxa + dya * dya, 1e-12);
1144
+ if (la >= params.distanceMax2) { continue; }
1145
+ if (la < params.distanceMin2) { la = sqrt(params.distanceMin2 * la); }
1146
+ let ca = params.strength * adjMass * params.alpha / la;
1147
+ accum.x = accum.x + dxa * ca;
1148
+ accum.y = accum.y + dya * ca;
1149
+ continue;
1150
+ }
1151
+ // Leaf cell: apply COM aggregate (mass nodes). Self-interaction guard:
1152
+ // if leaf contains only this query node, COM == queryPos \u2192 dx=dy=0 \u2192 skip.
1153
+ let isSelf = (mass < 1.5) && (abs(dx) < 1e-6) && (abs(dy) < 1e-6);
1154
+ if (isSelf) { continue; }
1155
+ var l2 = l;
1156
+ if (l2 >= params.distanceMax2) { continue; }
1157
+ if (l2 < params.distanceMin2) { l2 = sqrt(params.distanceMin2 * l2); }
1158
+ let c = params.strength * mass * params.alpha / l2;
1159
+ accum.x = accum.x + dx * c;
1160
+ accum.y = accum.y + dy * c;
1161
+ continue;
1162
+ }
1163
+
1164
+ // Descend into 4 children. Children of cell at Morton M, level k are at
1165
+ // level k+1, Morton M*4..M*4+3, stored at levelOffsets[k+1] + M*4 + c.
1166
+ let parentMorton = cellIdx - levelOffsets[level];
1167
+ let childBase = levelOffsets[level + 1u] + parentMorton * 4u;
1168
+ if (top + 4u <= MAX_STACK) {
1169
+ let nextLevel = level + 1u;
1170
+ for (var c: u32 = 0u; c < 4u; c = c + 1u) {
1171
+ stack[stackBase + top] = (nextLevel << 24u) | (childBase + c);
1172
+ top = top + 1u;
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ velocities[queryIdx] = vec4<f32>(
1178
+ velocities[queryIdx].x + accum.x,
1179
+ velocities[queryIdx].y + accum.y,
1180
+ velocities[queryIdx].z,
1181
+ velocities[queryIdx].w,
1182
+ );
1183
+ }
1184
+ `,ln=8,J=64,ce=64,ee=4;function cn(e){return Math.floor((Math.pow(4,e+1)-1)/3)}function V(e){return Math.floor((Math.pow(4,e)-1)/3)}var dn=class{constructor(e,n=ln){this.accumParamsBufs=[],this.accumBGs=[],this.config={strength:-30,theta:.9,distanceMin:1,distanceMax:1/0},this.device=e.device,this.nodeCount=e.nodeCount,this.maxLevel=n,this.totalCells=cn(n);let r=this.device,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST;this.cellsBuffer=r.createBuffer({label:"quad-cells",size:this.totalCells*ee*4,usage:t}),this.boundsBuffer=r.createBuffer({label:"quad-bounds",size:32,usage:t}),this.levelOffsetsBuffer=r.createBuffer({label:"quad-level-offsets",size:(n+1)*4,usage:t});let a=new Uint32Array(n+1);for(let h=0;h<=n;h++)a[h]=V(h);r.queue.writeBuffer(this.levelOffsetsBuffer,0,a),this.boundsParamsBuf=r.createBuffer({label:"quad-bounds-params",size:16,usage:i}),this.clearParamsBuf=r.createBuffer({label:"quad-clear-params",size:16,usage:i}),this.binParamsBuf=r.createBuffer({label:"quad-bin-params",size:16,usage:i}),this.traverseParamsBuf=r.createBuffer({label:"quad-traverse-params",size:48,usage:i});for(let h=0;h<n;h++){let d=r.createBuffer({label:`quad-accum-params-L${h}`,size:16,usage:i}),b=new Uint32Array([V(h),V(h+1),Math.pow(4,h),0]);r.queue.writeBuffer(d,0,b),this.accumParamsBufs.push(d)}let s=this.totalCells*ee,u=Math.ceil(s/J)*J;r.queue.writeBuffer(this.clearParamsBuf,0,new Uint32Array([s,u,0,0]));let l=(h,d)=>r.createShaderModule({label:h,code:d}),m=(h,d,b="main")=>r.createComputePipeline({label:h,layout:"auto",compute:{module:d,entryPoint:b}});this.boundsPipeline=m("quad-bounds-pipe",l("quad-bounds",se)),this.clearPipeline=m("quad-clear-pipe",l("quad-clear",pe)),this.binPipeline=m("quad-bin-pipe",l("quad-bin",sn)),this.accumPipeline=m("quad-accum-pipe",l("quad-accum",on)),this.traversePipeline=m("quad-traverse-pipe",l("quad-traverse",un)),this.bindAll(e)}bindAll(e){let n=this.device;this.boundsBG=n.createBindGroup({layout:this.boundsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:this.boundsBuffer}},{binding:2,resource:{buffer:this.boundsParamsBuf}}]}),this.clearBG=n.createBindGroup({layout:this.clearPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.clearParamsBuf}}]}),this.binBG=n.createBindGroup({layout:this.binPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:this.cellsBuffer}},{binding:2,resource:{buffer:this.boundsBuffer}},{binding:3,resource:{buffer:this.binParamsBuf}}]});for(let t=0;t<this.maxLevel;t++)this.accumBGs.push(n.createBindGroup({layout:this.accumPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.accumParamsBufs[t]}}]}));this.traverseBG=n.createBindGroup({layout:this.traversePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:e.velocityBuffer}},{binding:2,resource:{buffer:this.cellsBuffer}},{binding:3,resource:{buffer:this.levelOffsetsBuffer}},{binding:4,resource:{buffer:this.boundsBuffer}},{binding:5,resource:{buffer:this.traverseParamsBuf}}]});let r=new ArrayBuffer(16);new Uint32Array(r,0,3).set([this.nodeCount,this.maxLevel,V(this.maxLevel)]),new Float32Array(r,12,1)[0]=ce,n.queue.writeBuffer(this.binParamsBuf,0,r),n.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]))}setConfig(e){Object.assign(this.config,e)}apply(e,n){let r=this.device,t=this.nodeCount,i=J,a=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);r.queue.writeBuffer(this.boundsBuffer,0,a),this.run(n,this.boundsPipeline,this.boundsBG,Math.ceil(t/i),"quad-p1-bounds"),this.run(n,this.clearPipeline,this.clearBG,Math.ceil(this.totalCells*ee/i),"quad-p2-clear"),this.run(n,this.binPipeline,this.binBG,Math.ceil(t/i),"quad-p3-bin");for(let l=this.maxLevel-1;l>=0;l--)this.run(n,this.accumPipeline,this.accumBGs[l],Math.ceil(Math.pow(4,l)/i),`quad-p4-accum-L${l}`);let s=new ArrayBuffer(48),o=new Uint32Array(s),u=new Float32Array(s);o[0]=t,o[1]=this.maxLevel,u[4]=this.config.strength,u[5]=e,u[6]=this.config.theta*this.config.theta,u[7]=this.config.distanceMin*this.config.distanceMin,u[8]=this.config.distanceMax===1/0?1e30:this.config.distanceMax*this.config.distanceMax,u[9]=ce,r.queue.writeBuffer(this.traverseParamsBuf,0,s),this.run(n,this.traversePipeline,this.traverseBG,Math.ceil(t/i),"quad-p5-traverse")}run(e,n,r,t,i){let a=e.beginComputePass({label:i});a.setPipeline(n),a.setBindGroup(0,r),a.dispatchWorkgroups(t),a.end()}dispose(){this.cellsBuffer.destroy(),this.boundsBuffer.destroy(),this.levelOffsetsBuffer.destroy(),this.boundsParamsBuf.destroy(),this.clearParamsBuf.destroy(),this.binParamsBuf.destroy(),this.traverseParamsBuf.destroy(),this.accumParamsBufs.forEach(e=>e.destroy())}};function fn(){let e=-30,n=1,r=1/0,t=.9,i=null,a={initialize(s,o,u){},initGPU(s){i?.dispose(),i=new dn(s),i.setConfig({strength:e,theta:t,distanceMin:n,distanceMax:r})},apply(s,o){i?.apply(s,o)},dispose(){i?.dispose(),i=null},strength(s){return arguments.length===0?e:(e=+s,i?.setConfig({strength:e}),a)},distanceMin(s){return arguments.length===0?n:(n=+s,i?.setConfig({distanceMin:n}),a)},distanceMax(s){return arguments.length===0?r:(r=+s,i?.setConfig({distanceMax:r}),a)},theta(s){return arguments.length===0?t:(t=+s,i?.setConfig({theta:t}),a)}};return a}var pn=`// oct-bin: 3D version of quad-bin. Per-node atomic write of (x, y, z, mass)
1185
+ // into the LEAF cell at MAX level of a fixed-depth 3D octree.
1186
+ // Cell address: leafOffset + morton3D(cellX, cellY, cellZ).
1187
+
1188
+ struct BinParams {
1189
+ nodeCount: u32,
1190
+ maxLevel: u32,
1191
+ leafOffset: u32,
1192
+ fixedScale: f32,
1193
+ };
1194
+
1195
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
1196
+ @group(0) @binding(1) var<storage, read_write> cells: array<atomic<i32>>;
1197
+ @group(0) @binding(2) var<storage, read> bounds: array<i32, 6>;
1198
+ @group(0) @binding(3) var<uniform> params: BinParams;
1199
+
1200
+ fn orderedIntToFloat(i: i32) -> f32 {
1201
+ return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
1202
+ }
1203
+
1204
+ // 10-bit value \u2192 30-bit interleaved (each input bit at every 3rd output bit).
1205
+ fn mortonExpand10(v: u32) -> u32 {
1206
+ var x = v & 0x3FFu;
1207
+ x = (x | (x << 16u)) & 0x030000FFu;
1208
+ x = (x | (x << 8u)) & 0x0300F00Fu;
1209
+ x = (x | (x << 4u)) & 0x030C30C3u;
1210
+ x = (x | (x << 2u)) & 0x09249249u;
1211
+ return x;
1212
+ }
1213
+
1214
+ @compute @workgroup_size(64)
1215
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
1216
+ let i = gid.x;
1217
+ if (i >= params.nodeCount) { return; }
1218
+
1219
+ let xMin = orderedIntToFloat(bounds[0]);
1220
+ let xMax = orderedIntToFloat(bounds[1]);
1221
+ let yMin = orderedIntToFloat(bounds[2]);
1222
+ let yMax = orderedIntToFloat(bounds[3]);
1223
+ let zMin = orderedIntToFloat(bounds[4]);
1224
+ let zMax = orderedIntToFloat(bounds[5]);
1225
+ let spanX = max(xMax - xMin, 1e-9);
1226
+ let spanY = max(yMax - yMin, 1e-9);
1227
+ let spanZ = max(zMax - zMin, 1e-9);
1228
+
1229
+ let p = positions[i].xyz;
1230
+ let levelSize = 1u << params.maxLevel;
1231
+ let n01 = clamp(
1232
+ vec3<f32>((p.x - xMin) / spanX, (p.y - yMin) / spanY, (p.z - zMin) / spanZ),
1233
+ vec3<f32>(0.0), vec3<f32>(0.999999));
1234
+ let cellXi = u32(n01.x * f32(levelSize));
1235
+ let cellYi = u32(n01.y * f32(levelSize));
1236
+ let cellZi = u32(n01.z * f32(levelSize));
1237
+ let mortonIdx =
1238
+ mortonExpand10(cellXi)
1239
+ | (mortonExpand10(cellYi) << 1u)
1240
+ | (mortonExpand10(cellZi) << 2u);
1241
+
1242
+ let cellArrayIdx = params.leafOffset + mortonIdx;
1243
+ let baseSlot = cellArrayIdx * 4u;
1244
+
1245
+ // Store raw \`p * fixedScale\` (legacy semantics).
1246
+ let xFixed = i32(p.x * params.fixedScale);
1247
+ let yFixed = i32(p.y * params.fixedScale);
1248
+ let zFixed = i32(p.z * params.fixedScale);
1249
+ atomicAdd(&cells[baseSlot + 0u], xFixed);
1250
+ atomicAdd(&cells[baseSlot + 1u], yFixed);
1251
+ atomicAdd(&cells[baseSlot + 2u], zFixed);
1252
+ atomicAdd(&cells[baseSlot + 3u], 1i);
1253
+ }
1254
+ `,hn=`// oct-accumulate: bottom-up COM aggregation for 3D octree.
1255
+ //
1256
+ // Mirrors d3-force-3d's manyBody accumulate:
1257
+ // strength += child.value;
1258
+ // strength *= Math.sqrt(4 / numChildren); // 0.707 for octree (8 children)
1259
+ //
1260
+ // Implemented by scaling the parent's accumulated MASS by sqrt(4/8) = 0.707 in
1261
+ // fixed-point. (Sum_x/Sum_y/Sum_z keep the un-scaled position-weighted sums;
1262
+ // COM at traverse is sum/mass, so mass scaling makes the force F = strength *
1263
+ // mass * alpha / l\xB2 also scale by 0.707 \u2014 matching d3 exactly.)
1264
+
1265
+ struct AccumParams {
1266
+ parentOffset: u32,
1267
+ childOffset: u32,
1268
+ parentCount: u32, // 8^k
1269
+ _pad: u32,
1270
+ };
1271
+
1272
+ @group(0) @binding(0) var<storage, read_write> cells: array<atomic<i32>>;
1273
+ @group(0) @binding(1) var<uniform> params: AccumParams;
1274
+
1275
+ @compute @workgroup_size(64)
1276
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
1277
+ let pi = gid.x;
1278
+ if (pi >= params.parentCount) { return; }
1279
+
1280
+ let parentBase = (params.parentOffset + pi) * 4u;
1281
+ let child0Base = (params.childOffset + pi * 8u) * 4u;
1282
+
1283
+ var sx: i32 = 0;
1284
+ var sy: i32 = 0;
1285
+ var sz: i32 = 0;
1286
+ var sm: i32 = 0;
1287
+ for (var c: u32 = 0u; c < 8u; c = c + 1u) {
1288
+ let cb = child0Base + c * 4u;
1289
+ sx = sx + atomicLoad(&cells[cb + 0u]);
1290
+ sy = sy + atomicLoad(&cells[cb + 1u]);
1291
+ sz = sz + atomicLoad(&cells[cb + 2u]);
1292
+ sm = sm + atomicLoad(&cells[cb + 3u]);
1293
+ }
1294
+ // Store UNSCALED sums + UNSCALED count. d3's sqrt(4/numChildren) scaling
1295
+ // is applied at FORCE APPLICATION time in oct-traverse using the cell's
1296
+ // level \u2014 keeps COM = sum/count correct (scaled COM would inflate positions).
1297
+ atomicStore(&cells[parentBase + 0u], sx);
1298
+ atomicStore(&cells[parentBase + 1u], sy);
1299
+ atomicStore(&cells[parentBase + 2u], sz);
1300
+ atomicStore(&cells[parentBase + 3u], sm);
1301
+ }
1302
+ `,mn=`// oct-traverse: per-query-node Barnes-Hut DFS over fixed-depth 3D octree.
1303
+ // Mirrors quad-traverse.wgsl with 8 children per cell + z axis.
1304
+ //
1305
+ // BH criterion uses MAX axis extent of bounds (cell width = boundsMax / 2^level).
1306
+
1307
+ struct TraverseParams {
1308
+ nodeCount: u32,
1309
+ maxLevel: u32,
1310
+ _pad0: u32,
1311
+ _pad1: u32,
1312
+ strength: f32,
1313
+ alpha: f32,
1314
+ theta2: f32,
1315
+ distanceMin2: f32,
1316
+ distanceMax2: f32,
1317
+ fixedScale: f32,
1318
+ _pad2: f32,
1319
+ _pad3: f32,
1320
+ };
1321
+
1322
+ @group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
1323
+ @group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
1324
+ @group(0) @binding(2) var<storage, read_write> cells: array<atomic<i32>>;
1325
+ @group(0) @binding(3) var<storage, read> levelOffsets: array<u32>;
1326
+ @group(0) @binding(4) var<storage, read> bounds: array<i32, 6>;
1327
+ @group(0) @binding(5) var<uniform> params: TraverseParams;
1328
+
1329
+ fn orderedIntToFloat(i: i32) -> f32 {
1330
+ return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
1331
+ }
1332
+
1333
+ // 10-bit value \u2192 30-bit interleaved (kept in sync with oct-bin.wgsl). Used to
1334
+ // compute the query's own leaf cellIdx so the leaf-level branch can subtract
1335
+ // the query's contribution from the cell COM, avoiding the d3-force-3d
1336
+ // non-conformance where multiple nodes share a fixed-depth leaf and the BH
1337
+ // approximation feeds back through the query's own position (the historical
1338
+ // "cross-star" artifact on dense graphs \u2014 see
1339
+ // .harness/knowledge/gpu_force_cross_star_known_limit.md).
1340
+ fn mortonExpand10(v: u32) -> u32 {
1341
+ var x = v & 0x3FFu;
1342
+ x = (x | (x << 16u)) & 0x030000FFu;
1343
+ x = (x | (x << 8u)) & 0x0300F00Fu;
1344
+ x = (x | (x << 4u)) & 0x030C30C3u;
1345
+ x = (x | (x << 2u)) & 0x09249249u;
1346
+ return x;
1347
+ }
1348
+
1349
+ // Workgroup memory: 64 \xD7 56 \xD7 4 = 14 KB (under 16 KB limit).
1350
+ // MAX_STACK = 56 covers worst-case DFS depth (7\xB7L + 1 = 50 for L=7) with margin.
1351
+ // Pack (level, cellIdx) into single u32 \u2014 level high 8 bits, cellIdx low 24.
1352
+ // Octree at L=7: total cells = (8^8-1)/7 = 2,396,745 = 22 bits; fits in 24.
1353
+ const WG_SIZE: u32 = 64u;
1354
+ const MAX_STACK: u32 = 56u;
1355
+ var<workgroup> stack: array<u32, 3584>; // WG_SIZE \xD7 MAX_STACK
1356
+
1357
+ @compute @workgroup_size(64)
1358
+ fn main(
1359
+ @builtin(global_invocation_id) gid: vec3<u32>,
1360
+ @builtin(local_invocation_index) lid: u32,
1361
+ ) {
1362
+ let queryIdx = gid.x;
1363
+ if (queryIdx >= params.nodeCount) { return; }
1364
+
1365
+ let qp = positions[queryIdx].xyz;
1366
+ var accum = vec3<f32>(0.0, 0.0, 0.0);
1367
+ let stackBase = lid * MAX_STACK;
1368
+ let invScale = 1.0 / params.fixedScale;
1369
+
1370
+ let xMin = orderedIntToFloat(bounds[0]);
1371
+ let xMax = orderedIntToFloat(bounds[1]);
1372
+ let yMin = orderedIntToFloat(bounds[2]);
1373
+ let yMax = orderedIntToFloat(bounds[3]);
1374
+ let zMin = orderedIntToFloat(bounds[4]);
1375
+ let zMax = orderedIntToFloat(bounds[5]);
1376
+ let boundsMax = max(xMax - xMin, max(yMax - yMin, zMax - zMin));
1377
+
1378
+ // Precompute the query's own leaf cellIdx using the same Morton mapping as
1379
+ // oct-bin.wgsl. At leaf level we use this to detect "the cell containing me"
1380
+ // and subtract self-contribution from the COM (leaf-COM fix).
1381
+ let spanXq = max(xMax - xMin, 1e-9);
1382
+ let spanYq = max(yMax - yMin, 1e-9);
1383
+ let spanZq = max(zMax - zMin, 1e-9);
1384
+ let levelSizeMax = 1u << params.maxLevel;
1385
+ let n01q = clamp(
1386
+ vec3<f32>((qp.x - xMin) / spanXq, (qp.y - yMin) / spanYq, (qp.z - zMin) / spanZq),
1387
+ vec3<f32>(0.0), vec3<f32>(0.999999));
1388
+ let qcx = u32(n01q.x * f32(levelSizeMax));
1389
+ let qcy = u32(n01q.y * f32(levelSizeMax));
1390
+ let qcz = u32(n01q.z * f32(levelSizeMax));
1391
+ let queryMorton =
1392
+ mortonExpand10(qcx)
1393
+ | (mortonExpand10(qcy) << 1u)
1394
+ | (mortonExpand10(qcz) << 2u);
1395
+ let queryLeafCellIdx = levelOffsets[params.maxLevel] + queryMorton;
1396
+
1397
+ var top: u32 = 0u;
1398
+ stack[stackBase + top] = 0u; // root: level=0, cellIdx=0
1399
+ top = top + 1u;
1400
+
1401
+ loop {
1402
+ if (top == 0u) { break; }
1403
+ top = top - 1u;
1404
+ let packed = stack[stackBase + top];
1405
+ let level = packed >> 24u;
1406
+ let cellIdx = packed & 0x00FFFFFFu;
1407
+
1408
+ let cb = cellIdx * 4u;
1409
+ let count = f32(atomicLoad(&cells[cb + 3u])); // UN-SCALED count (true node count)
1410
+ if (count < 0.5) { continue; }
1411
+ let sumX = f32(atomicLoad(&cells[cb + 0u])) * invScale;
1412
+ let sumY = f32(atomicLoad(&cells[cb + 1u])) * invScale;
1413
+ let sumZ = f32(atomicLoad(&cells[cb + 2u])) * invScale;
1414
+ let comX = sumX / count;
1415
+ let comY = sumY / count;
1416
+ let comZ = sumZ / count;
1417
+
1418
+ // d3-force-3d dim scaling: effective mass at level k = count \xD7 sqrt(0.5)^(maxLevel-level).
1419
+ // Leaf (level==maxLevel): factor = 1. Root (level=0): factor = 0.7071^6 \u2248 0.125.
1420
+ // Applied here (not in accumulate) so COM = sum/count stays correct.
1421
+ let depthFromLeaf = params.maxLevel - level;
1422
+ var dimFactor: f32 = 1.0;
1423
+ for (var d: u32 = 0u; d < depthFromLeaf; d = d + 1u) {
1424
+ dimFactor = dimFactor * 0.7071067811865476;
1425
+ }
1426
+ let mass = count * dimFactor;
1427
+
1428
+ let levelSize = f32(1u << level);
1429
+ let cellWidth = boundsMax / levelSize;
1430
+
1431
+ let dx = comX - qp.x;
1432
+ let dy = comY - qp.y;
1433
+ let dz = comZ - qp.z;
1434
+ let l = max(dx * dx + dy * dy + dz * dz, 1e-12);
1435
+
1436
+ if (cellWidth * cellWidth < l * params.theta2) {
1437
+ var l2 = l;
1438
+ if (l2 >= params.distanceMax2) { continue; }
1439
+ if (l2 < params.distanceMin2) { l2 = sqrt(params.distanceMin2 * l2); }
1440
+ let c = params.strength * mass * params.alpha / l2;
1441
+ accum = accum + vec3<f32>(dx, dy, dz) * c;
1442
+ continue;
1443
+ }
1444
+
1445
+ if (level >= params.maxLevel) {
1446
+ // Leaf-COM fix: when this leaf is the cell containing the query node,
1447
+ // subtract the query's own (x, y, z, 1) contribution from the cell's
1448
+ // sum/count so the effective COM is the centroid of the OTHER nodes.
1449
+ // Without this, multi-node leaves bias every query toward the axis from
1450
+ // itself to the leaf centroid \u2192 axis-aligned "cross-star" rays on dense
1451
+ // graphs at large N. (d3-force-3d's recursive subdivision keeps leaves
1452
+ // at \u22641 node; this fixed-depth port emulates that semantics here.)
1453
+ if (cellIdx == queryLeafCellIdx) {
1454
+ let adjCount = count - 1.0;
1455
+ if (adjCount < 0.5) { continue; } // query was the sole occupant
1456
+ let adjSumX = sumX - qp.x;
1457
+ let adjSumY = sumY - qp.y;
1458
+ let adjSumZ = sumZ - qp.z;
1459
+ let adjComX = adjSumX / adjCount;
1460
+ let adjComY = adjSumY / adjCount;
1461
+ let adjComZ = adjSumZ / adjCount;
1462
+ let dxa = adjComX - qp.x;
1463
+ let dya = adjComY - qp.y;
1464
+ let dza = adjComZ - qp.z;
1465
+ var la = max(dxa * dxa + dya * dya + dza * dza, 1e-12);
1466
+ if (la >= params.distanceMax2) { continue; }
1467
+ if (la < params.distanceMin2) { la = sqrt(params.distanceMin2 * la); }
1468
+ // dimFactor == 1.0 at leaf, so effective mass = adjCount.
1469
+ let ca = params.strength * adjCount * params.alpha / la;
1470
+ accum = accum + vec3<f32>(dxa, dya, dza) * ca;
1471
+ continue;
1472
+ }
1473
+ let isSelf = (mass < 1.5) && (abs(dx) < 1e-6) && (abs(dy) < 1e-6) && (abs(dz) < 1e-6);
1474
+ if (isSelf) { continue; }
1475
+ var l2 = l;
1476
+ if (l2 >= params.distanceMax2) { continue; }
1477
+ if (l2 < params.distanceMin2) { l2 = sqrt(params.distanceMin2 * l2); }
1478
+ let c = params.strength * mass * params.alpha / l2;
1479
+ accum = accum + vec3<f32>(dx, dy, dz) * c;
1480
+ continue;
1481
+ }
1482
+
1483
+ // Descend into 8 children. Children of cell at Morton M, level k are at
1484
+ // level k+1, Morton M*8..M*8+7, stored at levelOffsets[k+1] + M*8 + c.
1485
+ let parentMorton = cellIdx - levelOffsets[level];
1486
+ let childBase = levelOffsets[level + 1u] + parentMorton * 8u;
1487
+ if (top + 8u <= MAX_STACK) {
1488
+ let nextLevel = level + 1u;
1489
+ for (var c: u32 = 0u; c < 8u; c = c + 1u) {
1490
+ stack[stackBase + top] = (nextLevel << 24u) | (childBase + c);
1491
+ top = top + 1u;
1492
+ }
1493
+ }
1494
+ }
1495
+
1496
+ velocities[queryIdx] = vec4<f32>(
1497
+ velocities[queryIdx].x + accum.x,
1498
+ velocities[queryIdx].y + accum.y,
1499
+ velocities[queryIdx].z + accum.z,
1500
+ velocities[queryIdx].w,
1501
+ );
1502
+ }
1503
+ `,gn=7,ne=64,de=64,Ln=Math.sqrt(.5);function bn(e){return Math.floor((Math.pow(8,e+1)-1)/7)}function K(e){return Math.floor((Math.pow(8,e)-1)/7)}var te=4,ie=65535,yn=class{constructor(e,n=gn){this.accumParamsBufs=[],this.accumBGs=[],this.config={strength:-30,theta:.9,distanceMin:1,distanceMax:1/0},this.device=e.device,this.nodeCount=e.nodeCount,this.maxLevel=n,this.totalCells=bn(n);let r=this.device,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST;this.cellsBuffer=r.createBuffer({label:"oct-cells",size:this.totalCells*te*4,usage:t}),this.boundsBuffer=r.createBuffer({label:"oct-bounds",size:32,usage:t}),this.levelOffsetsBuffer=r.createBuffer({label:"oct-level-offsets",size:(n+1)*4,usage:t});let a=new Uint32Array(n+1);for(let d=0;d<=n;d++)a[d]=K(d);r.queue.writeBuffer(this.levelOffsetsBuffer,0,a),this.boundsParamsBuf=r.createBuffer({label:"oct-bounds-params",size:16,usage:i}),this.clearParamsBuf=r.createBuffer({label:"oct-clear-params",size:16,usage:i}),this.binParamsBuf=r.createBuffer({label:"oct-bin-params",size:16,usage:i}),this.traverseParamsBuf=r.createBuffer({label:"oct-traverse-params",size:48,usage:i});for(let d=0;d<n;d++){let b=r.createBuffer({label:`oct-accum-params-L${d}`,size:16,usage:i}),P=new ArrayBuffer(16),g=new Uint32Array(P);g[0]=K(d),g[1]=K(d+1),g[2]=Math.pow(8,d),r.queue.writeBuffer(b,0,P),this.accumParamsBufs.push(b)}let s=this.totalCells*te,o=Math.ceil(s/ne),l=Math.min(o,ie)*ne;r.queue.writeBuffer(this.clearParamsBuf,0,new Uint32Array([s,l,0,0]));let m=(d,b)=>r.createShaderModule({label:d,code:b}),h=(d,b,P="main")=>r.createComputePipeline({label:d,layout:"auto",compute:{module:b,entryPoint:P}});this.boundsPipeline=h("oct-bounds-pipe",m("oct-bounds",se)),this.clearPipeline=h("oct-clear-pipe",m("oct-clear",pe)),this.binPipeline=h("oct-bin-pipe",m("oct-bin",pn)),this.accumPipeline=h("oct-accum-pipe",m("oct-accum",hn)),this.traversePipeline=h("oct-traverse-pipe",m("oct-traverse",mn)),this.bindAll(e)}bindAll(e){let n=this.device;this.boundsBG=n.createBindGroup({layout:this.boundsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:this.boundsBuffer}},{binding:2,resource:{buffer:this.boundsParamsBuf}}]}),this.clearBG=n.createBindGroup({layout:this.clearPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.clearParamsBuf}}]}),this.binBG=n.createBindGroup({layout:this.binPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:this.cellsBuffer}},{binding:2,resource:{buffer:this.boundsBuffer}},{binding:3,resource:{buffer:this.binParamsBuf}}]});for(let t=0;t<this.maxLevel;t++)this.accumBGs.push(n.createBindGroup({layout:this.accumPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.accumParamsBufs[t]}}]}));this.traverseBG=n.createBindGroup({layout:this.traversePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:e.velocityBuffer}},{binding:2,resource:{buffer:this.cellsBuffer}},{binding:3,resource:{buffer:this.levelOffsetsBuffer}},{binding:4,resource:{buffer:this.boundsBuffer}},{binding:5,resource:{buffer:this.traverseParamsBuf}}]}),n.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]));let r=new ArrayBuffer(16);new Uint32Array(r,0,3).set([this.nodeCount,this.maxLevel,K(this.maxLevel)]),new Float32Array(r,12,1)[0]=de,n.queue.writeBuffer(this.binParamsBuf,0,r)}setConfig(e){Object.assign(this.config,e)}apply(e,n){let r=this.device,t=this.nodeCount,i=ne,a=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);r.queue.writeBuffer(this.boundsBuffer,0,a),this.run(n,this.boundsPipeline,this.boundsBG,Math.ceil(t/i),"oct-p1-bounds");let s=Math.ceil(this.totalCells*te/i),o=Math.min(s,ie),u=Math.ceil(s/ie);this.run2D(n,this.clearPipeline,this.clearBG,o,u,"oct-p2-clear"),this.run(n,this.binPipeline,this.binBG,Math.ceil(t/i),"oct-p3-bin");for(let d=this.maxLevel-1;d>=0;d--)this.run(n,this.accumPipeline,this.accumBGs[d],Math.ceil(Math.pow(8,d)/i),`oct-p4-accum-L${d}`);let l=new ArrayBuffer(48),m=new Uint32Array(l),h=new Float32Array(l);m[0]=t,m[1]=this.maxLevel,h[4]=this.config.strength,h[5]=e,h[6]=this.config.theta*this.config.theta,h[7]=this.config.distanceMin*this.config.distanceMin,h[8]=this.config.distanceMax===1/0?1e30:this.config.distanceMax*this.config.distanceMax,h[9]=de,r.queue.writeBuffer(this.traverseParamsBuf,0,l),this.run(n,this.traversePipeline,this.traverseBG,Math.ceil(t/i),"oct-p5-traverse")}run(e,n,r,t,i){let a=e.beginComputePass({label:i});a.setPipeline(n),a.setBindGroup(0,r),a.dispatchWorkgroups(t),a.end()}run2D(e,n,r,t,i,a){let s=e.beginComputePass({label:a});s.setPipeline(n),s.setBindGroup(0,r),s.dispatchWorkgroups(t,i,1),s.end()}dispose(){this.cellsBuffer.destroy(),this.boundsBuffer.destroy(),this.levelOffsetsBuffer.destroy(),this.boundsParamsBuf.destroy(),this.clearParamsBuf.destroy(),this.binParamsBuf.destroy(),this.traverseParamsBuf.destroy(),this.accumParamsBufs.forEach(e=>e.destroy())}};function vn(){let e=-30,n=1,r=1/0,t=.9,i=null,a={initialize(s,o,u){},initGPU(s){i?.dispose(),i=new yn(s),i.setConfig({strength:e,theta:t,distanceMin:n,distanceMax:r})},apply(s,o){i?.apply(s,o)},dispose(){i?.dispose(),i=null},strength(s){return arguments.length===0?e:(e=+s,i?.setConfig({strength:e}),a)},distanceMin(s){return arguments.length===0?n:(n=+s,i?.setConfig({distanceMin:n}),a)},distanceMax(s){return arguments.length===0?r:(r=+s,i?.setConfig({distanceMax:r}),a)},theta(s){return arguments.length===0?t:(t=+s,i?.setConfig({theta:t}),a)}};return a}var xn={charge:-.01,gravity:.1,linkStrength:1,linkDistance:.5,collision:.15,heightCompress:1,alpha:.6,alphaDecay:.1,velocityDecay:.3,dimensions:3,gravityX:1,gravityY:1,gravityZ:1,octreeTheta:.9},W=240;function Bn(e,n,r){let t=globalThis,i=t.__webgpuPathATiming;i||(i={tick:new Float32Array(W),read:new Float32Array(W),sync:new Float32Array(W),i:0,filled:0,reset(){this.i=0,this.filled=0},summary(){let a=this.filled;if(a===0)return null;let s=o=>{let u=0,l=1/0,m=-1/0;for(let h=0;h<a;h++){let d=o[h];u+=d,d<l&&(l=d),d>m&&(m=d)}return{mean:+(u/a).toFixed(3),min:+l.toFixed(3),max:+m.toFixed(3),n:a}};return{skipFlag:!!globalThis.__webgpuPathASkip,tickMs:s(this.tick),readMs:s(this.read),syncMs:s(this.sync),totalMs:{mean:+(this.tick.reduce((o,u)=>o+u,0)/a+this.read.reduce((o,u)=>o+u,0)/a+this.sync.reduce((o,u)=>o+u,0)/a).toFixed(3)}}}},t.__webgpuPathATiming=i),i.tick[i.i]=e,i.read[i.i]=n,i.sync[i.i]=r,i.i=(i.i+1)%W,i.filled<W&&i.filled++}var Dn=class{constructor(e,n,r={}){if(this.sharedArray=new Float32Array(0),this.nodeIdToIndex=new Map,this.isFinish=!1,this._enable=!0,this.getOptions=()=>null,this._readbackTimingSink=null,this.simulation=null,this.simNodes=[],this._loopRunning=!1,this._currentSpaceSize=10,this.forceCharge=null,this.forceLinkInstance=null,this.forceXInstance=null,this.forceYInstance=null,this.forceZInstance=null,this.forceCenterInstance=null,this._linkDegree=new Int32Array(0),this._linkStrengthFn=t=>{let i=t.source,a=t.target,s=Math.min(this._linkDegree[i]??1,this._linkDegree[a]??1);return this.params.linkStrength*(s>0?1/s:1)},this._readbackTickCounter=0,!re())throw new Error("[WebGPUForceLayoutController] navigator.gpu unavailable in this environment. Use the WebGL-backed GPUForceLayoutController instead.");this.params={...xn},this.options=r,this.graph=e??{layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!0}}setReadbackTimingSink(e){return this._readbackTimingSink=e,this}config(e){this.getOptions=e;let n=e();return n&&this.applyConfig(n),this}configure(e){return this.config(e)}applyConfig(e){e.charge!==void 0&&(this.params.charge=e.charge),e.gravity!==void 0&&(this.params.gravity=e.gravity),e.linkStrength!==void 0&&(this.params.linkStrength=e.linkStrength),e.linkDistance!==void 0&&(this.params.linkDistance=e.linkDistance),e.collision!==void 0&&(this.params.collision=e.collision),e.heightCompress!==void 0&&(this.params.heightCompress=e.heightCompress),e.alpha!==void 0&&(this.params.alpha=e.alpha),e.alphaDecay!==void 0&&(this.params.alphaDecay=e.alphaDecay),e.velocityDecay!==void 0&&(this.params.velocityDecay=e.velocityDecay),e.friction!==void 0&&(this.params.velocityDecay=e.friction),e.dimensions!==void 0&&(this.params.dimensions=e.dimensions),e.gravityX!==void 0&&(this.params.gravityX=e.gravityX),e.gravityY!==void 0&&(this.params.gravityY=e.gravityY),e.gravityZ!==void 0&&(this.params.gravityZ=e.gravityZ),e.octreeTheta!==void 0&&(this.params.octreeTheta=e.octreeTheta)}startLayout(e=0,n=0,r=!1){let t=this.params.dimensions,i=this.getOptions();i&&this.applyConfig(i),this.params.dimensions=t,this.disposeSimulation(),this.buildSimulation(r),this.simulation&&(this._enable=!0,this.isFinish=!1,this.graph.renderNeedsUpdate=!0,this._loopRunning=!1,this.runLoop())}restartLayout(){if(!this._enable)return;let e=this.getOptions();if(e){let t=this.params.dimensions;this.applyConfig(e),this.params.dimensions=t}this.applyForceParams();let n=this.graph.layoutNodes.length,r=this.simNodes.length;this.simulation&&n===r?(this.simulation.alpha(this.params.alpha),this.isFinish=!1,this.graph.renderNeedsUpdate=!0,this.runLoop()):this.startLayout()}stopLayout(){this._enable=!1,this.isFinish=!0,this.graph.renderNeedsUpdate=!1}destroy(){this.stopLayout(),this.disposeSimulation()}disposeSimulation(){this.simulation?.dispose(),this.simulation=null,this.forceCharge=null,this.forceLinkInstance=null,this.forceXInstance=null,this.forceYInstance=null,this.forceZInstance=null,this.forceCenterInstance=null}buildSimulation(e=!1){let n=this.graph.layoutNodes,r=this.graph.layoutEdges,t=n.length;if(t===0)return;let i=this.params.dimensions,a=n.some(g=>Math.abs(g.position.z)>1e-6),s=i>2&&!a&&!e,o=Math.cbrt(n.length)*2,l=Math.min(10,Math.pow(2,29)/(Math.pow(t,1.5)*64)),m=i===2&&!s&&!e,h=Math.PI*(3-Math.sqrt(5));this.simNodes=n.map((g,f)=>{let p={id:g.id,index:f};if(g.pinned)p.fx=g.position.x,p.fy=g.position.y,p.fz=g.position.z,p.x=g.position.x,p.y=g.position.y,p.z=g.position.z;else if(s){let x=Math.random(),B=Math.random(),G=Math.random(),F=2*Math.PI*x,z=Math.acos(2*B-1),w=Math.cbrt(G)*o;p.x=w*Math.sin(z)*Math.cos(F),p.y=w*Math.sin(z)*Math.sin(F),p.z=w*Math.cos(z)}else if(m){let x=l*Math.sqrt(.5+f),B=f*h;p.x=x*Math.cos(B),p.y=x*Math.sin(B),p.z=0}else e&&(p.x=g.position.x,p.y=g.position.y,p.z=i<=2?0:g.position.z);return p}),this.nodeIdToIndex.clear();for(let g=0;g<t;g++)this.nodeIdToIndex.set(this.simNodes[g].id,g*3);this.sharedArray=new Float32Array(t*3),this._currentSpaceSize=Math.max(10,2*(this.params.dimensions===2?10*Math.sqrt(t):10*Math.cbrt(t)));let d=ve(this.simNodes,this.params.dimensions,{device:this.options.device});d.alpha(this.params.alpha).alphaDecay(this.params.alphaDecay).velocityDecay(this.params.velocityDecay).alphaTarget(0).maxVel(this.staticMaxVel(this.simNodes.length));let{forcexy:b,forcez:P}=this.calculateAxisForces();if(this.forceXInstance=Ae(0).strength(b*this.params.gravityX),this.forceYInstance=Fe(0).strength(b*this.params.gravityY),d.force("x",this.forceXInstance),d.force("y",this.forceYInstance),this.params.dimensions>2&&(this.forceZInstance=ze(0).strength(P*this.params.gravityZ),d.force("z",this.forceZInstance)),this.forceCharge=this.makeChargeForce(t),d.force("charge",this.forceCharge),r.length){let g=r.map(p=>{let x=this.nodeIdToIndex.get(p.sourceId),B=this.nodeIdToIndex.get(p.targetId);return x===void 0||B===void 0?null:{id:p.id,source:x/3,target:B/3}}).filter(p=>p!==null),f=g.length;this._linkDegree=new Int32Array(t);for(let p=0;p<f;p++)this._linkDegree[g[p].source]++,this._linkDegree[g[p].target]++;this.forceLinkInstance=Ue(g).strength(this._linkStrengthFn).distance(this.params.linkDistance),d.force("link",this.forceLinkInstance)}this.forceCenterInstance=Ce(0,0,0).strength(1),d.force("center",this.forceCenterInstance),this.simulation=d}makeChargeForce(e){if(this.params.dimensions===2){let r=fn();return r.theta?.(this.params.octreeTheta),r.strength(this.params.charge),r}if(e>=1e4){let r=an();return r.theta(this.params.octreeTheta),r.strength(this.params.charge),r}let n=vn();return n.theta?.(this.params.octreeTheta),n.strength(this.params.charge),n}calculateAxisForces(){let e,n;if(this.params.dimensions===2)e=this.params.gravity*1.5,n=0;else{let r=this.params.heightCompress;n=Math.min(10,this.params.gravity*Math.sqrt(r)),e=this.params.gravity/Math.sqrt(r)}return{forcexy:e,forcez:n}}applyForceParams(){if(!this.simulation)return;this.simulation.alphaDecay(this.params.alphaDecay),this.simulation.velocityDecay(this.params.velocityDecay);let{forcexy:e,forcez:n}=this.calculateAxisForces();this.forceXInstance?.strength(e*this.params.gravityX),this.forceYInstance?.strength(e*this.params.gravityY),this.forceZInstance?.strength(n*this.params.gravityZ),this.forceCharge?.strength(this.params.charge),this.forceLinkInstance&&(this.forceLinkInstance.strength(this._linkStrengthFn),this.forceLinkInstance.distance(this.params.linkDistance))}afterTick(e){let n=this.options.onTick;if(n)try{n({positionBuffer:e.getPositionBuffer(),nodeCount:this.simNodes.length})}catch{}}async runLoop(){if(!this._loopRunning){this._loopRunning=!0;try{let e=this.simulation;for(e&&!e.isReady()&&await new Promise(n=>e.on("ready",()=>n()));this._enable&&this.simulation&&(await this.waitForFrame(),!!this._enable);){let n=this.simulation;if(!n)break;let r=performance.now();n.tick(1),this.afterTick(n);let t=performance.now(),i=Math.max(1,Math.floor(globalThis.__webgpuReadbackInterval??1));this._readbackTickCounter++;let a=this._readbackTickCounter>=i,s=n.alpha()<n.alphaMin(),o=a||s,u=t,l=t;if(o){this._readbackTickCounter=0;try{await n.readPositions()}catch(m){console.warn("[WebGPUForceLayoutController] readPositions threw, skipping:",m);continue}if(n!==this.simulation||!this._enable)break;u=performance.now(),this.syncPositionsToSharedArray(),l=performance.now(),this.graph.renderNeedsUpdate=!0}if(Bn(t-r,u-t,l-u),o&&this._readbackTimingSink)try{this._readbackTimingSink(l-t)}catch{}if(s){this.isFinish=!0,this.graph.renderNeedsUpdate=!1;break}}}finally{this._loopRunning=!1}}}waitForFrame(){return new Promise(e=>requestAnimationFrame(()=>e()))}syncPositionsToSharedArray(){let e=this.sharedArray,n=this.graph.layoutNodes,r=this.simNodes,t=Math.min(e.length/3,r.length,n.length);if(globalThis.__webgpuPathASkip===!0){let a=0;for(let s=0;s<e.length;s++){let o=e[s],u=o<0?-o:o;u>a&&(a=u)}this._currentSpaceSize=Math.max(10,2*a);return}let i=0;for(let a=0;a<t;a++){let s=r[a],o=s.x??0,u=s.y??0,l=s.z??0;e[a*3]=o,e[a*3+1]=u,e[a*3+2]=l;let m=n[a];m?.position&&(m.position.x=o,m.position.y=u,m.position.z=l);let h=Math.max(Math.abs(o),Math.abs(u),Math.abs(l));h>i&&(i=h)}this._currentSpaceSize=Math.max(10,2*i)}staticMaxVel(e){let n=this.params.dimensions===2?Math.max(10,Math.sqrt(e)*.5):Math.max(10,Math.cbrt(e)*2);return Math.min(2,n*.1)}updateLayoutOption(e,n){if(e==="friction"?this.params.velocityDecay=n:this.params[e]=n,!this.simulation||!this._enable)return;let r=()=>{this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop()};switch(e){case"charge":this.forceCharge?.strength(n),r();break;case"linkDistance":this.forceLinkInstance?.distance(n),r();break;case"linkStrength":this.forceLinkInstance?.strength(this._linkStrengthFn),r();break;case"gravity":case"gravityX":case"gravityY":case"gravityZ":case"heightCompress":{let{forcexy:t,forcez:i}=this.calculateAxisForces();this.forceXInstance?.strength(t*this.params.gravityX),this.forceYInstance?.strength(t*this.params.gravityY),this.forceZInstance?.strength(i*this.params.gravityZ),r();break}case"velocityDecay":case"friction":this.simulation.velocityDecay(this.params.velocityDecay);break;case"alpha":case"alphaDecay":this.restartLayout();return;default:this.restartLayout();return}this.graph.renderNeedsUpdate=!0}pinNodes(e){this.simulation&&(e.forEach(n=>{let r=this.nodeIdToIndex.get(n.id);if(r===void 0)return;let t=r/3,i=this.simNodes[t];i&&(n.pinned?(i.fx=n.position.x,i.fy=n.position.y,i.fz=n.position.z,i.x=n.position.x,i.y=n.position.y,i.z=n.position.z,this.simulation.uploadPosition(t,n.position.x,n.position.y,n.position.z),this.simulation.uploadPinned(t,!0)):(delete i.fx,delete i.fy,delete i.fz,this.simulation.uploadPinned(t,!1)))}),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop(),this.graph.renderNeedsUpdate=!0)}unpinNodes(e){this.simulation&&(e.forEach(n=>{let r=this.nodeIdToIndex.get(n);if(r===void 0)return;let t=r/3,i=this.simNodes[t];i&&(delete i.fx,delete i.fy,delete i.fz,this.simulation.uploadPinned(t,!1))}),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop(),this.graph.renderNeedsUpdate=!0)}transitionDimensions(e,n=600){this.params.dimensions!==e&&(e===2?(this.readBackPositions(),this.params.dimensions=2,this.startLayout(0,0,!0)):(this.readBackPositions(),this.params.dimensions=3,this.startLayout()))}cancelDimensionTransition(){}getDimensions(){return this.params.dimensions}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return this._currentSpaceSize}readBackPositions(){if(this.simNodes.length===0)return;this.syncPositionsToSharedArray();let e=this.params.dimensions,n=this.graph.layoutNodes;for(let r=0;r<this.simNodes.length;r++){let t=this.simNodes[r],i=n[r];!i||!i.position||(i.position.x=t.x??0,i.position.y=t.y??0,i.position.z=e>2?t.z??0:0)}}setExpectedNodeCount(e){}clearExpectedNodeCount(){}updateGraph(e,n,r=!1){this.graph.layoutNodes=e,this.graph.layoutEdges=n}},En=class{constructor(e){this.c=e,this.mode="cpu"}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return this.c.getSpaceSize()}get sharedArray(){return this.c.sharedArray}getPositions(){return this.c.sharedArray}tick(){}start(){this.c.startLayout()}restart(){this.c.restartLayout()}stop(){this.c.stopLayout()}get graph(){return this.c.graph}get needsUpdate(){return!this.c.isFinish}clearNeedsUpdate(){}pinNodes(e){this.c.pinNodes(e)}unpinNodes(e){this.c.unpinNodes(e)}readBackPositions(){this.c.readBackPositions()}transitionDimensions(e,n){this.c.transitionDimensions(e,n)}getDimensions(){return this.c.getDimensions()}updateOption(e,n){this.c.updateLayoutOption(e,n)}};export{re as a,he as b,Pn as c,Mn as d,_n as e,wn as f,Cn as g,kn as h,In as i,Sn as j,An as k,oe as l,Fn as m,zn as n,Tn as o,Gn as p,ve as q,Ce as r,Ae as s,Fe as t,ze as u,Ue as v,qn as w,an as x,Dn as y,En as z};
1504
+ //# sourceMappingURL=chunk-EDTCHJCZ.mjs.map