@kineviz/gl 0.7.0 → 0.7.1
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.
- package/CHANGELOG.md +636 -1
- package/dist/chunk-3CR3GHJ2.mjs +2 -0
- package/dist/index.d.mts +1552 -127
- package/dist/index.d.ts +1552 -127
- package/dist/index.js +640 -106
- package/dist/index.mjs +615 -81
- package/dist/kineviz-gl.umd.js +493 -324
- package/dist/layout-gpu.js +45 -45
- package/dist/layout-gpu.mjs +12 -12
- package/dist/schemas.js +1 -1
- package/dist/schemas.mjs +1 -1
- package/package.json +1 -1
package/dist/layout-gpu.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Qn=Object.create;var Ve=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ni=Object.prototype.hasOwnProperty;var ii=(e,t)=>{for(var n in t)Ve(e,n,{get:t[n],enumerable:!0})},Rt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ei(t))!ni.call(e,r)&&r!==n&&Ve(e,r,{get:()=>t[r],enumerable:!(i=Jn(t,r))||i.enumerable});return e};var pe=(e,t,n)=>(n=e!=null?Qn(ti(e)):{},Rt(t||!e||!e.__esModule?Ve(n,"default",{value:e,enumerable:!0}):n,e)),ri=e=>Rt(Ve({},"__esModule",{value:!0}),e);var Qr={};ii(Qr,{GPUForceLayoutController:()=>It,GPUForceLayoutEngine:()=>Wn,GPULayoutControllerAdapter:()=>Dt,WebGPUForceLayoutController:()=>ot,WebGPULayoutControllerAdapter:()=>st,createForceLayout:()=>Vn,isWebGPUAvailable:()=>Pe});module.exports=ri(Qr);function ai(e){var t=0,n=e.children,i=n&&n.length;if(!i)t=1;else for(;--i>=0;)t+=n[i].value;e.value=t}function Ut(){return this.eachAfter(ai)}function Lt(e,t){let n=-1;for(let i of this)e.call(t,i,++n,this);return this}function Gt(e,t){for(var n=this,i=[n],r,o,a=-1;n=i.pop();)if(e.call(t,n,++a,this),r=n.children)for(o=r.length-1;o>=0;--o)i.push(r[o]);return this}function Nt(e,t){for(var n=this,i=[n],r=[],o,a,s,l=-1;n=i.pop();)if(r.push(n),o=n.children)for(a=0,s=o.length;a<s;++a)i.push(o[a]);for(;n=r.pop();)e.call(t,n,++l,this);return this}function qt(e,t){let n=-1;for(let i of this)if(e.call(t,i,++n,this))return i}function Ot(e){return this.eachAfter(function(t){for(var n=+e(t.data)||0,i=t.children,r=i&&i.length;--r>=0;)n+=i[r].value;t.value=n})}function Ht(e){return this.eachBefore(function(t){t.children&&t.children.sort(e)})}function Xt(e){for(var t=this,n=oi(t,e),i=[t];t!==n;)t=t.parent,i.push(t);for(var r=i.length;e!==n;)i.splice(r,0,e),e=e.parent;return i}function oi(e,t){if(e===t)return e;var n=e.ancestors(),i=t.ancestors(),r=null;for(e=n.pop(),t=i.pop();e===t;)r=e,e=n.pop(),t=i.pop();return r}function Yt(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t}function $t(){return Array.from(this)}function Zt(){var e=[];return this.eachBefore(function(t){t.children||e.push(t)}),e}function jt(){var e=this,t=[];return e.each(function(n){n!==e&&t.push({source:n.parent,target:n})}),t}function*Vt(){var e=this,t,n=[e],i,r,o;do for(t=n.reverse(),n=[];e=t.pop();)if(yield e,i=e.children)for(r=0,o=i.length;r<o;++r)n.push(i[r]);while(n.length)}function dt(e,t){e instanceof Map?(e=[void 0,e],t===void 0&&(t=ui)):t===void 0&&(t=li);for(var n=new we(e),i,r=[n],o,a,s,l;i=r.pop();)if((a=t(i.data))&&(l=(a=Array.from(a)).length))for(i.children=a,s=l-1;s>=0;--s)r.push(o=a[s]=new we(a[s])),o.parent=i,o.depth=i.depth+1;return n.eachBefore(ft)}function si(){return dt(this).eachBefore(ci)}function li(e){return e.children}function ui(e){return Array.isArray(e)?e[1]:null}function ci(e){e.data.value!==void 0&&(e.value=e.data.value),e.data=e.data.data}function ft(e){var t=0;do e.height=t;while((e=e.parent)&&e.height<++t)}function we(e){this.data=e,this.depth=this.height=0,this.parent=null}we.prototype=dt.prototype={constructor:we,count:Ut,each:Lt,eachAfter:Nt,eachBefore:Gt,find:qt,sum:Ot,sort:Ht,path:Xt,ancestors:Yt,descendants:$t,leaves:Zt,links:jt,copy:si,[Symbol.iterator]:Vt};function We(e){return e==null?null:di(e)}function di(e){if(typeof e!="function")throw new Error;return e}var fi={depth:-1},Wt={},pt={};function pi(e){return e.id}function hi(e){return e.parentId}function mt(){var e=pi,t=hi,n;function i(r){var o=Array.from(r),a=e,s=t,l,u,c,d,f,p,g,m,y=new Map;if(n!=null){let M=o.map((v,b)=>mi(n(v,b,r))),S=M.map(Kt),h=new Set(M).add("");for(let v of S)h.has(v)||(h.add(v),M.push(v),S.push(Kt(v)),o.push(pt));a=(v,b)=>M[b],s=(v,b)=>S[b]}for(c=0,l=o.length;c<l;++c)u=o[c],p=o[c]=new we(u),(g=a(u,c,r))!=null&&(g+="")&&(m=p.id=g,y.set(m,y.has(m)?Wt:p)),(g=s(u,c,r))!=null&&(g+="")&&(p.parent=g);for(c=0;c<l;++c)if(p=o[c],g=p.parent){if(f=y.get(g),!f)throw new Error("missing: "+g);if(f===Wt)throw new Error("ambiguous: "+g);f.children?f.children.push(p):f.children=[p],p.parent=f}else{if(d)throw new Error("multiple roots");d=p}if(!d)throw new Error("no root");if(n!=null){for(;d.data===pt&&d.children.length===1;)d=d.children[0],--l;for(let M=o.length-1;M>=0&&(p=o[M],p.data===pt);--M)p.data=null}if(d.parent=fi,d.eachBefore(function(M){M.depth=M.parent.depth+1,--l}).eachBefore(ft),d.parent=null,l>0)throw new Error("cycle");return d}return i.id=function(r){return arguments.length?(e=We(r),i):e},i.parentId=function(r){return arguments.length?(t=We(r),i):t},i.path=function(r){return arguments.length?(n=We(r),i):n},i}function mi(e){e=`${e}`;let t=e.length;return ht(e,t-1)&&!ht(e,t-2)&&(e=e.slice(0,-1)),e[0]==="/"?e:`/${e}`}function Kt(e){let t=e.length;if(t<2)return"";for(;--t>1&&!ht(e,t););return e.slice(0,t)}function ht(e,t){if(e[t]==="/"){let n=0;for(;t>0&&e[--t]==="\\";)++n;if((n&1)===0)return!0}return!1}function gi(e,t){return e.parent===t.parent?1:2}function gt(e){var t=e.children;return t?t[0]:e.t}function yt(e){var t=e.children;return t?t[t.length-1]:e.t}function yi(e,t,n){var i=n/(t.i-e.i);t.c-=i,t.s+=n,e.c+=i,t.z+=n,t.m+=n}function vi(e){for(var t=0,n=0,i=e.children,r=i.length,o;--r>=0;)o=i[r],o.z+=t,o.m+=t,t+=o.s+(n+=o.c)}function xi(e,t,n){return e.a.parent===t.parent?e.a:n}function Ke(e,t){this._=e,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=t}Ke.prototype=Object.create(we.prototype);function bi(e){for(var t=new Ke(e,0),n,i=[t],r,o,a,s;n=i.pop();)if(o=n._.children)for(n.children=new Array(s=o.length),a=s-1;a>=0;--a)i.push(r=n.children[a]=new Ke(o[a],a)),r.parent=n;return(t.parent=new Ke(null,0)).children=[t],t}function vt(){var e=gi,t=1,n=1,i=null;function r(u){var c=bi(u);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),i)u.eachBefore(l);else{var d=u,f=u,p=u;u.eachBefore(function(S){S.x<d.x&&(d=S),S.x>f.x&&(f=S),S.depth>p.depth&&(p=S)});var g=d===f?1:e(d,f)/2,m=g-d.x,y=t/(f.x+g+m),M=n/(p.depth||1);u.eachBefore(function(S){S.x=(S.x+m)*y,S.y=S.depth*M})}return u}function o(u){var c=u.children,d=u.parent.children,f=u.i?d[u.i-1]:null;if(c){vi(u);var p=(c[0].z+c[c.length-1].z)/2;f?(u.z=f.z+e(u._,f._),u.m=u.z-p):u.z=p}else f&&(u.z=f.z+e(u._,f._));u.parent.A=s(u,f,u.parent.A||d[0])}function a(u){u._.x=u.z+u.parent.m,u.m+=u.parent.m}function s(u,c,d){if(c){for(var f=u,p=u,g=c,m=f.parent.children[0],y=f.m,M=p.m,S=g.m,h=m.m,v;g=yt(g),f=gt(f),g&&f;)m=gt(m),p=yt(p),p.a=u,v=g.z+S-f.z-y+e(g._,f._),v>0&&(yi(xi(g,u,d),u,v),y+=v,M+=v),S+=g.m,y+=f.m,h+=m.m,M+=p.m;g&&!yt(p)&&(p.t=g,p.m+=S-M),f&&!gt(m)&&(m.t=f,m.m+=y-h,d=u)}return d}function l(u){u.x*=t,u.y=u.depth*n}return r.separation=function(u){return arguments.length?(e=u,r):e},r.size=function(u){return arguments.length?(i=!1,t=+u[0],n=+u[1],r):i?null:[t,n]},r.nodeSize=function(u){return arguments.length?(i=!0,t=+u[0],n=+u[1],r):i?[t,n]:null},r}var Ue=pe(require("lodash"),1);var wi={value:()=>{}};function Jt(){for(var e=0,t=arguments.length,n={},i;e<t;++e){if(!(i=arguments[e]+"")||i in n||/[\s.]/.test(i))throw new Error("illegal type: "+i);n[i]=[]}return new Qe(n)}function Qe(e){this._=e}function _i(e,t){return e.trim().split(/^|\s+/).map(function(n){var i="",r=n.indexOf(".");if(r>=0&&(i=n.slice(r+1),n=n.slice(0,r)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:i}})}Qe.prototype=Jt.prototype={constructor:Qe,on:function(e,t){var n=this._,i=_i(e+"",n),r,o=-1,a=i.length;if(arguments.length<2){for(;++o<a;)if((r=(e=i[o]).type)&&(r=Si(n[r],e.name)))return r;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<a;)if(r=(e=i[o]).type)n[r]=Qt(n[r],e.name,t);else if(t==null)for(r in n)n[r]=Qt(n[r],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Qe(e)},call:function(e,t){if((r=arguments.length-2)>0)for(var n=new Array(r),i=0,r,o;i<r;++i)n[i]=arguments[i+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],i=0,r=o.length;i<r;++i)o[i].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var i=this._[e],r=0,o=i.length;r<o;++r)i[r].value.apply(t,n)}};function Si(e,t){for(var n=0,i=e.length,r;n<i;++n)if((r=e[n]).name===t)return r.value}function Qt(e,t,n){for(var i=0,r=e.length;i<r;++i)if(e[i].name===t){e[i]=wi,e=e.slice(0,i).concat(e.slice(i+1));break}return n!=null&&e.push({name:t,value:n}),e}var xt=Jt;var Ae=0,He=0,Oe=0,tn=1e3,Je,Xe,et=0,ze=0,tt=0,Ye=typeof performance=="object"&&performance.now?performance:Date,nn=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function wt(){return ze||(nn(Ti),ze=Ye.now()+tt)}function Ti(){ze=0}function bt(){this._call=this._time=this._next=null}bt.prototype=nt.prototype={constructor:bt,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?wt():+n)+(t==null?0:+t),!this._next&&Xe!==this&&(Xe?Xe._next=this:Je=this,Xe=this),this._call=e,this._time=n,Mt()},stop:function(){this._call&&(this._call=null,this._time=1/0,Mt())}};function nt(e,t,n){var i=new bt;return i.restart(e,t,n),i}function rn(){wt(),++Ae;for(var e=Je,t;e;)(t=ze-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Ae}function en(){ze=(et=Ye.now())+tt,Ae=He=0;try{rn()}finally{Ae=0,Bi(),ze=0}}function Pi(){var e=Ye.now(),t=e-et;t>tn&&(tt-=t,et=e)}function Bi(){for(var e,t=Je,n,i=1/0;t;)t._call?(i>t._time&&(i=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Je=n);Xe=e,Mt(i)}function Mt(e){if(!Ae){He&&(He=clearTimeout(He));var t=e-ze;t>24?(e<1/0&&(He=setTimeout(en,e-Ye.now()-tt)),Oe&&(Oe=clearInterval(Oe))):(Oe||(et=Ye.now(),Oe=setInterval(Pi,tn)),Ae=1,nn(en))}}function be(e){let t=0,n=0,i=0,r=0;for(let[,o]of e)t+=o[0],n+=o[1],i+=o[2],r++;return r===0?[0,0,0]:[t/r,n/r,i/r]}var Se=1;function xe(e,t){let n=new Map;for(let i=0;i<e.nodes.length;i++)n.set(e.nodes[i].id,t[i]);return{positions:n}}function an(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=t?.spacing??Se,o=t?.radius??Math.max(r,n*r/(2*Math.PI)),a=Math.PI*2/n,s=[];for(let l=0;l<n;l++)s.push([o*Math.cos(l*a)+i[0],o*Math.sin(l*a)+i[1],0]);return xe(e,s)}function on(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=t?.columns&&t.columns>0?t.columns:Math.ceil(Math.sqrt(n)),o=t?.spacing??Se,a=o*(r-1),s=[];for(let l=0;l<n;l++)s.push([l%r*o-a/2+i[0],-Math.floor(l/r)*o+a/2+i[1],0]);return xe(e,s)}function sn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=t?.axis??"x",o=t?.spacing??Se,a=o*(n-1),s=[];for(let l=0;l<n;l++){let u=n>1?-a/2+l*o:0,c=[i[0],i[1],i[2]],d=r==="x"?0:r==="y"?1:2;c[d]=u+i[d],s.push(c)}return xe(e,s)}function ln(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=t?.spacing??1.5,o=r/(2*Math.PI),a=2*Math.PI,s=[];for(let l=0;l<n;l++){let u=o*a;s.push([u*Math.cos(a)+i[0],u*Math.sin(a)+i[1],0]),a+=r/u}return xe(e,s)}function un(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=Math.cbrt(n),o=Math.floor(r),a=Math.ceil(r),s=t?.size??(n-Math.pow(o,3)>Math.pow(a,3)-n?a:o),l=t?.spacing??Se,u=l*Math.max(s-1,0),c=[];for(let d=0;d<n;d++)c.push([d%s*l-u/2+i[0],-(Math.floor(d/s)%s)*l+u/2+i[1],-Math.floor(d/(s*s))*l+u/2+i[2]]);return xe(e,c)}function cn(e,t){let n=e.nodes.length;if(n<=1){let l=new Map;return n===1&&l.set(e.nodes[0].id,e.positions.get(e.nodes[0].id)??[0,0,0]),{positions:l}}let i=be(e.positions),r=t?.spacing??Se,o=t?.density!==void 0?Math.sqrt(n/(4*Math.PI*t.density)):r*Math.sqrt(n/(4*Math.PI)),a=t?.radius??Math.max(r,o),s=[];for(let l=0;l<n;l++){let u=Math.acos(1-(2*(l+1)-1)/n),c=Math.sqrt(n*Math.PI)*u;s.push([a*Math.sin(u)*Math.cos(c)+i[0],a*Math.sin(u)*Math.sin(c)+i[1],a*Math.cos(u)+i[2]])}return xe(e,s)}function dn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=t?.spacing??Se,r=t?.range??Math.max(i,i*Math.cbrt(n)/2),o=t?.seed??42;function a(){o|=0,o=o+1831565813|0;let l=Math.imul(o^o>>>15,1|o);return l=l+Math.imul(l^l>>>7,61|l)^l,((l^l>>>14)>>>0)/4294967296}let s=[];for(let l=0;l<n;l++)s.push([(a()-.5)*r*2,(a()-.5)*r*2,(a()-.5)*r*2]);return xe(e,s)}function fn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.axis??"x",r=(t?.degrees??90)*Math.PI/180,o=be(e.positions),a=[];for(let s of e.nodes){let l=e.positions.get(s.id)??[0,0,0],u=l[0]-o[0],c=l[1]-o[1],d=l[2]-o[2],f,p,g,m=Math.cos(r),y=Math.sin(r);i==="x"?(f=u,p=c*m-d*y,g=c*y+d*m):i==="y"?(f=u*m+d*y,p=c,g=-u*y+d*m):(f=u*m-c*y,p=u*y+c*m,g=d),a.push([f+o[0],p+o[1],g+o[2]])}return xe(e,a)}function pn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.factor,r=i??t?.x??1,o=i??t?.y??1,a=i??t?.z??1,s=be(e.positions),l=[];for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0];l.push([c[0]+(c[0]-s[0])*(r-1),c[1]+(c[1]-s[1])*(o-1),c[2]+(c[2]-s[2])*(a-1)])}return xe(e,l)}function hn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.x??0,r=t?.y??0,o=t?.z??0,a=[];for(let s of e.nodes){let l=e.positions.get(s.id)??[0,0,0];a.push([l[0]+i,l[1]+r,l[2]+o])}return xe(e,a)}function mn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.axis??"x",r=i==="x"?0:i==="y"?1:2,o=1/0,a=-1/0;for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0];c[r]<o&&(o=c[r]),c[r]>a&&(a=c[r])}let s=(o+a)/2,l=[];for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0],d=[c[0],c[1],c[2]];d[r]=s,l.push(d)}return xe(e,l)}function gn(e,t){let{depth:n=100,mode:i="tree",orientation:r="right",alongRelationships:o=[]}=t??{},a=t?.spacing??Se,s=t?.spacing===void 0?t?.edgeLength:void 0,l=e.nodes;if(l.length===0)return{positions:new Map};let u=new Set;for(let[x]of e.positions)u.add(x);let c=new Map,d=new Map;for(let x of e.edges)!u.has(x.source)||!u.has(x.target)||(d.set(x.id,x),c.has(x.source)||c.set(x.source,[]),c.has(x.target)||c.set(x.target,[]),c.get(x.source).push({nodeId:x.target,relationship:x.relationship}),c.get(x.target).push({nodeId:x.source,relationship:x.relationship}));let f=o.length>0?new Set(Array.from(c.entries()).filter(([,x])=>x.some(({relationship:E})=>o.includes(E))).map(([x])=>x)):u,p=l.filter(x=>f.has(x.id));if(p.length===0)return{positions:new Map};let g=new Map,m=p.map(x=>[{from:"",to:x.id}]),y=p.map(x=>[[x.id]]),M=p.map(()=>1),S=p.map(()=>[1]),h=p.map(x=>x.id),v=1;for(;v<=n&&Ue.sum(y.map(x=>x[v-1]?.length??0))>0;)y.forEach((x,E)=>{let F=x[v-1];if(!F)return;let R=[];F.forEach(A=>{let I=c.get(A)??[],L=I.map(({nodeId:B})=>B);o.length>0&&(L=I.filter(({relationship:B})=>o.includes(B)).map(({nodeId:B})=>B)),L=Ue.difference(Ue.intersection(L,Array.from(f)),h),L.forEach(B=>{m[E].push({from:A,to:B}),R.push(B),h.push(B)})}),x[v]=R,R.length>0&&(S[E].push(R.length),M[E]++)}),v++;let b=mt().id(x=>x.to).parentId(x=>x.from||null);return p.forEach((x,E)=>{let F=e.positions.get(x.id)??[0,0,0];if(m[E].length<=1){g.set(x.id,[F[0],F[1],F[2]]);return}let R;try{R=b(m[E])}catch{g.set(x.id,[F[0],F[1],F[2]]);return}let A=Math.max(...S[E],1),I=Math.max(M[E]-1,1),L=Math.max(A-1,1),B,k;i==="rings"?(B=2*Math.PI,s!==void 0?k=s*I:k=Math.max(a,a*A/(2*Math.PI))):s!==void 0?(B=s*A*.2*Math.pow(M[E],.3),k=s*I):(B=a*L,k=a*I);let z=vt().size([B,k])(R);yn(i,r,z,z,F,g)}),{positions:g}}function yn(e,t,n,i,r,o){let a=i.id,s,l;if(e==="tree")switch(t){case"up":s=i.x+r[0]-n.x,l=i.y+r[1]+n.y;break;case"down":s=-i.x+r[0]+n.x,l=-i.y+r[1]-n.y;break;case"right":s=i.y+r[0]-n.y,l=-i.x+r[1]+n.x;break;case"left":s=-i.y+r[0]+n.y,l=i.x+r[1]-n.x;break}else switch(t){case"down":s=r[0]+i.y*Math.cos(i.x+Math.PI/2),l=r[1]+i.y*Math.sin(i.x+Math.PI/2);break;case"up":s=r[0]+i.y*Math.cos(i.x+3*Math.PI/2),l=r[1]+i.y*Math.sin(i.x+3*Math.PI/2);break;case"right":s=r[0]+i.y*Math.cos(i.x+Math.PI),l=r[1]+i.y*Math.sin(i.x+Math.PI);break;case"left":s=r[0]+i.y*Math.cos(i.x),l=r[1]+i.y*Math.sin(i.x);break}if(o.set(a,[s,l,r[2]]),i.children)for(let u of i.children)yn(e,t,n,u,r,o)}function _e(e){if(e==null)return null;let t=Number(e);return Number.isNaN(t)?null:t}function Ce(e,t,n){let[i,r]=t,[o,a]=n;return r===i?(o+a)/2:o+(e-i)/(r-i)*(a-o)}function ke(e,t,n){let i=Math.max(t[0],1e-10),r=Math.max(t[1],1e-10),o=Math.max(e,1e-10),[a,s]=n;return r===i?(a+s)/2:a+(Math.log(o)-Math.log(i))/(Math.log(r)-Math.log(i))*(s-a)}function vn(e,t,n){let i=n??_e,r=1/0,o=-1/0;for(let a of e){let s=a.properties?.[t],l=i(s);l!=null&&(l<r&&(r=l),l>o&&(o=l))}return r===1/0?[0,1]:r===o?[r-1,o+1]:[r,o]}function xn(e,t=5){let[n,i]=e,r=i-n;if(r===0)return[n-1,i+1];let o=r/t,a=Math.pow(10,Math.floor(Math.log10(o))),s=o/a,l;return s<=1.5?l=a:s<=3.5?l=2*a:s<=7.5?l=5*a:l=10*a,[Math.floor(n/l)*l,Math.ceil(i/l)*l]}function bn(e,t=5){let[n,i]=e;if(n===i)return[n];let o=(i-n)/t,a=Math.pow(10,Math.floor(Math.log10(o))),s=o/a,l;s<=1.5?l=a:s<=3.5?l=2*a:s<=7.5?l=5*a:l=10*a;let u=Math.ceil(n/l)*l,c=[];for(let d=u;d<=i+l*.001;d+=l)c.push(Math.round(d*1e10)/1e10);return c}var _t=[{name:"1s",ms:1e3},{name:"5s",ms:5e3},{name:"15s",ms:15e3},{name:"30s",ms:3e4},{name:"1m",ms:6e4},{name:"5m",ms:3e5},{name:"15m",ms:9e5},{name:"30m",ms:18e5},{name:"1h",ms:36e5},{name:"3h",ms:108e5},{name:"6h",ms:216e5},{name:"12h",ms:432e5},{name:"1d",ms:864e5},{name:"3d",ms:2592e5},{name:"1w",ms:6048e5},{name:"1mo",ms:2592e6,calendarUnit:"month",calendarStep:1},{name:"3mo",ms:7776e6,calendarUnit:"month",calendarStep:3},{name:"6mo",ms:15552e6,calendarUnit:"month",calendarStep:6},{name:"1y",ms:31536e6,calendarUnit:"year",calendarStep:1},{name:"2y",ms:63072e6,calendarUnit:"year",calendarStep:2},{name:"5y",ms:15768e7,calendarUnit:"year",calendarStep:5},{name:"10y",ms:31536e7,calendarUnit:"year",calendarStep:10},{name:"20y",ms:63072e7,calendarUnit:"year",calendarStep:20},{name:"50y",ms:15768e8,calendarUnit:"year",calendarStep:50}];function Mn(e,t=5){let[n,i]=e,r=i-n;if(r<=0)return[n];let o=r/t,a=_t[_t.length-1];for(let l of _t)if(l.ms>=o*.6){a=l;break}let s=[];if(a.calendarUnit==="year"){let l=a.calendarStep,u=new Date(n),c=Math.ceil(u.getFullYear()/l)*l;for(;;){let d=new Date(c,0,1).getTime();if(d>i)break;d>=n&&s.push(d),c+=l}}else if(a.calendarUnit==="month"){let l=a.calendarStep,u=new Date(n),c=u.getFullYear(),d=Math.ceil(u.getMonth()/l)*l;for(;;){let f=new Date(c,d,1).getTime();if(f>i)break;f>=n&&s.push(f),d+=l,d>=12&&(c+=Math.floor(d/12),d=d%12)}}else{let l=a.ms,u=Math.ceil(n/l)*l;for(let c=u;c<=i;c+=l)s.push(c)}return s}function wn(e,t){let n=t[1]-t[0],i=new Date(e);return n>365*864e5*2?String(i.getFullYear()):n>60*864e5?`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}`:n>2*864e5?`${i.getMonth()+1}/${i.getDate()}`:n>2*36e5?`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`:`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}:${String(i.getSeconds()).padStart(2,"0")}`}function Re(e,t,n){let i=e.domain??vn(t,e.property,e.parse);e.nice&&!e.domain&&(i=xn(i,e.tickCount));let o=(i[1]-i[0])*n,a=[i[0]-o,i[1]+o],s;e.tickValues?s=e.tickValues:e.isDate?s=Mn(i,e.tickCount):s=bn(i,e.tickCount);let l=e.tickFormat;return!l&&e.isDate&&(l=u=>wn(u,i)),{axisInfo:{property:e.property,label:e.property,domain:a,ticks:s,scale:e.scale,tickFormat:l},paddedDomain:a}}function _n(e,t){let{propertyX:n,propertyY:i,propertyZ:r,range:o=[-2,2],scaleX:a="linear",scaleY:s="linear",scaleZ:l="linear",padding:u=.05}=t,c=t.parseX??_e,d=t.parseY??_e,f=t.parseZ??_e,p=!!n,g=!!i,m=!!r,y=e.nodes,M=new Map,S=new Set,h=[];for(let B of y){let k=0,w=0,z=0,P=!1;if(p){let T=c(B.properties?.[n]);T==null?P=!0:k=T}if(g&&!P){let T=d(B.properties?.[i]);T==null?P=!0:w=T}if(m&&!P){let T=f(B.properties?.[r]);T==null?P=!0:z=T}P?S.add(B.id):h.push({id:B.id,x:k,y:w,z})}let v=p?Re({property:n,scale:a,domain:t.domainX,parse:c,tickFormat:t.tickFormatX,tickCount:t.tickCountX??5,tickValues:t.tickValuesX,nice:t.niceX??!0,isDate:t.dateAxisX??!1},y,u):null,b=g?Re({property:i,scale:s,domain:t.domainY,parse:d,tickFormat:t.tickFormatY,tickCount:t.tickCountY??5,tickValues:t.tickValuesY,nice:t.niceY??!0,isDate:t.dateAxisY??!1},y,u):null,x=m?Re({property:r,scale:l,domain:t.domainZ,parse:f,tickFormat:t.tickFormatZ,tickCount:t.tickCountZ??5,tickValues:t.tickValuesZ,nice:t.niceZ??!0,isDate:t.dateAxisZ??!1},y,u):null,E=a==="log"?ke:Ce,F=s==="log"?ke:Ce,R=l==="log"?ke:Ce,A=t.spread??1,I=[o[0]*A,o[1]*A],L=o[0];for(let B of h){let k=v?E(B.x,v.paddedDomain,I):L,w=b?F(B.y,b.paddedDomain,I):L,z=x?R(B.z,x.paddedDomain,I):0;M.set(B.id,[k,w,z])}return{positions:M,axes:{x:v?.axisInfo,y:b?.axisInfo,z:x?.axisInfo},range:I,baseRange:o,excludedNodeIds:S}}function Sn(e,t){let n=t.range??[-2,2],i=t.spread??1,r=[n[0]*i,n[1]*i],o=t.padding??.05,a=n[0],s=t.unmappedMode??"hide",l=new Map;for(let p of t.mappings)l.set(p.category,p);let u=new Map;for(let p of e.nodes){let g=p.category,m=u.get(g);m||(m=[],u.set(g,m)),m.push(p)}let c=new Map,d=new Set,f={};for(let[p,g]of u){let m=l.get(p);if(!m){if(s==="hide")for(let G of g)d.add(G.id);else{let G;s==="boundary"?G=n[0]:G=(n[0]+n[1])/2;for(let _ of g)c.set(_.id,[G,G,0])}continue}let y=!!m.propertyX,M=!!m.propertyY,S=!!m.propertyZ,h=m.scaleX??"linear",v=m.scaleY??"linear",b=m.scaleZ??"linear",x=m.parseX??_e,E=m.parseY??_e,F=m.parseZ??_e,R=m.tickCountX??t.tickCountX??5,A=m.tickCountY??t.tickCountY??5,I=m.tickCountZ??t.tickCountZ??5,L=m.niceX??t.niceX??!0,B=m.niceY??t.niceY??!0,k=m.niceZ??t.niceZ??!0,w=[];for(let G of g){let _=0,D=0,O=0,Y=!1;if(y){let X=x(G.properties?.[m.propertyX]);X==null?Y=!0:_=X}if(M&&!Y){let X=E(G.properties?.[m.propertyY]);X==null?Y=!0:D=X}if(S&&!Y){let X=F(G.properties?.[m.propertyZ]);X==null?Y=!0:O=X}Y?d.add(G.id):w.push({id:G.id,x:_,y:D,z:O})}let z=y?Re({property:m.propertyX,scale:h,domain:m.domainX,parse:x,tickFormat:m.tickFormatX,tickCount:R,tickValues:m.tickValuesX,nice:L,isDate:m.dateAxisX??!1},g,o):null,P=M?Re({property:m.propertyY,scale:v,domain:m.domainY,parse:E,tickFormat:m.tickFormatY,tickCount:A,tickValues:m.tickValuesY,nice:B,isDate:m.dateAxisY??!1},g,o):null,T=S?Re({property:m.propertyZ,scale:b,domain:m.domainZ,parse:F,tickFormat:m.tickFormatZ,tickCount:I,tickValues:m.tickValuesZ,nice:k,isDate:m.dateAxisZ??!1},g,o):null,C=h==="log"?ke:Ce,q=v==="log"?ke:Ce,N=b==="log"?ke:Ce;for(let G of w){let _=z?C(G.x,z.paddedDomain,r):a,D=P?q(G.y,P.paddedDomain,r):a,O=T?N(G.z,T.paddedDomain,r):0;c.set(G.id,[_,D,O])}f[p]={x:z?.axisInfo,y:P?.axisInfo,z:T?.axisInfo}}return{positions:c,axes:{x:void 0,y:void 0,z:void 0},range:r,baseRange:n,excludedNodeIds:d,categoryAxes:f}}var zi=/^[a-z][a-zA-Z0-9]*$/,Ci=/^[a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9_-]*$/,Tn=class Pn{constructor(){this.entries=new Map}register(t,n,i={}){if(!Ci.test(t))throw new Error(`[LayoutRegistry] invalid layout name "${t}": extension layouts must be named "<pack>:<name>" (e.g. "acme:rack")`);return this.add(t,n,!1,i)}registerBuiltin(t,n,i){if(!zi.test(t))throw new Error(`[LayoutRegistry] invalid built-in layout name "${t}"`);this.add(t,n,!0,{description:i})}add(t,n,i,r){if(typeof n!="function")throw new Error(`[LayoutRegistry] layout "${t}" must be a function`);let o=this.entries.get(t);if(o&&(o.builtin||!r.replace))throw new Error(`[LayoutRegistry] layout "${t}" is already registered`);let a={name:t,fn:n,builtin:i,description:r.description};return this.entries.set(t,a),()=>{this.entries.get(t)===a&&this.entries.delete(t)}}has(t){return this.entries.has(t)}get(t){return this.entries.get(t)}list(){let t=[...this.entries.values()];return[...t.filter(n=>n.builtin),...t.filter(n=>!n.builtin)]}execute(t,n,i){let r=this.entries.get(t);if(!r)throw new Error(`[LayoutRegistry] unknown layout "${t}". Registered: ${[...this.entries.keys()].join(", ")}`);return r.fn(n,i)}fork(){let t=new Pn;for(let[n,i]of this.entries)t.entries.set(n,i);return t}};function ki(){let e=new Tn;return e.registerBuiltin("circle",an,"Nodes on a circle."),e.registerBuiltin("grid",on,"Nodes on a 2-D grid."),e.registerBuiltin("line",sn,"Nodes along an axis."),e.registerBuiltin("spiral",ln,"Nodes on a spiral."),e.registerBuiltin("cube",un,"Nodes in a 3-D lattice."),e.registerBuiltin("sphere",cn,"Nodes on a sphere."),e.registerBuiltin("scatter",dn,"Nodes scattered randomly in a range."),e.registerBuiltin("ego",gn,"Tree or rings around root node(s)."),e.registerBuiltin("rotate",fn,"Rotate current positions (transform)."),e.registerBuiltin("scale",pn,"Scale current positions (transform)."),e.registerBuiltin("shift",hn,"Translate current positions (transform)."),e.registerBuiltin("alignBy",mn,"Align nodes by an axis (transform)."),e.registerBuiltin("plotScatter",_n,"Scatter plot by two properties."),e.registerBuiltin("plotMultiCategoryScatter",Sn,"Scatter plot with category axes."),e}var Ei=ki();var re=pe(require("three"),1);function Pe(){return typeof navigator<"u"&&!!navigator.gpu}async function En(e={}){if(!Pe())throw new Error("WebGPU not available: navigator.gpu is undefined. Use the WebGL backend instead.");let t=await navigator.gpu.requestAdapter({powerPreference:e.preferHighPerformance===!1?"low-power":"high-performance"});if(!t)throw new Error("WebGPU adapter request returned null (no compatible adapter found).");let i=(e.requestedFeatures??[]).filter(o=>t.features.has(o)),r=await t.requestDevice({requiredFeatures:i});return{adapter:t,device:r,features:new Set(t.features),limits:t.limits}}function Ct(e){if(e<=0)return 1;let t=Math.ceil(Math.sqrt(e));return Math.pow(2,Math.ceil(Math.log2(t)))}function Ne(e,t,n=10){if(e<=0)return n;let i;return t===3?i=Math.cbrt(e)*2:i=Math.sqrt(e)*.5,Math.max(n,i)}function Fi(){return{type:re.FloatType,format:re.RGBAFormat,minFilter:re.NearestFilter,magFilter:re.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1}}function Ee(e){let t=Fi();return new re.WebGLRenderTarget(e,e,t)}function qe(e,t){let n=new re.DataTexture(e,t,t,re.RGBAFormat,re.FloatType);return n.minFilter=re.NearestFilter,n.magFilter=re.NearestFilter,n.needsUpdate=!0,n}function Fn(e){let t=[];for(let n=0;n<e;n++)for(let i=0;i<e;i++)t.push(i,n);return new Float32Array(t)}function ye(){return new re.PlaneGeometry(2,2)}function In(e=1){let r=e;return function(){return r=(1664525*r+1013904223)%4294967296,r/4294967296}}function at(e){return(e()-.5)*1e-6}function te(e){return()=>e}function Ze(e,t,n){let i=e.length,r=10,o=Math.PI*(3-Math.sqrt(5)),a=Math.PI*20/(9+Math.sqrt(221));for(let s=0;s<i;s++){let l=e[s];if(l.index=s,l.fx!=null&&(l.x=l.fx),l.fy!=null&&(l.y=l.fy),l.fz!=null&&(l.z=l.fz),isNaN(l.x)||t>1&&isNaN(l.y)||t>2&&isNaN(l.z)){let u=r*(t>2?Math.cbrt(.5+s):t>1?Math.sqrt(.5+s):s),c=s*o,d=s*a;t===1?l.x=u:t===2?(l.x=u*Math.cos(c),l.y=u*Math.sin(c)):(l.x=u*Math.sin(c)*Math.cos(d),l.y=u*Math.cos(c),l.z=u*Math.sin(c)*Math.sin(d))}(isNaN(l.vx)||t>1&&isNaN(l.vy)||t>2&&isNaN(l.vz))&&(l.vx=0,t>1&&(l.vy=0),t>2&&(l.vz=0))}}function Dn(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.x||0,i[a+1]=o.y||0,i[a+2]=o.z||0,i[a+3]=r}return i}function An(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.vx||0,i[a+1]=o.vy||0,i[a+2]=o.vz||0,i[a+3]=0}return i}function Rn(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.fx!=null||o.fy!=null||o.fz!=null?1:0,i[a+1]=0,i[a+2]=0,i[a+3]=0}return i}function Un(e,t,n){for(let i=0;i<e.length;i++){let r=e[i],o=i*4;r.fx==null&&(r.x=t[o]),n>1&&r.fy==null&&(r.y=t[o+1]),n>2&&r.fz==null?r.z=t[o+2]:n<=2&&(r.z=0)}}var Ii=`// Position integration compute shader.
|
|
1
|
+
"use strict";var pi=Object.create;var Ke=Object.defineProperty;var hi=Object.getOwnPropertyDescriptor;var mi=Object.getOwnPropertyNames;var gi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var vi=(e,t)=>{for(var n in t)Ke(e,n,{get:t[n],enumerable:!0})},Ot=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of mi(t))!yi.call(e,r)&&r!==n&&Ke(e,r,{get:()=>t[r],enumerable:!(i=hi(t,r))||i.enumerable});return e};var pe=(e,t,n)=>(n=e!=null?pi(gi(e)):{},Ot(t||!e||!e.__esModule?Ke(n,"default",{value:e,enumerable:!0}):n,e)),xi=e=>Ot(Ke({},"__esModule",{value:!0}),e);var va={};vi(va,{GPUForceLayoutController:()=>Gt,GPUForceLayoutEngine:()=>di,GPULayoutControllerAdapter:()=>Nt,WebGPUForceLayoutController:()=>ft,WebGPULayoutControllerAdapter:()=>pt,createForceLayout:()=>ci,isWebGPUAvailable:()=>Pe});module.exports=xi(va);function bi(e){var t=0,n=e.children,i=n&&n.length;if(!i)t=1;else for(;--i>=0;)t+=n[i].value;e.value=t}function Ht(){return this.eachAfter(bi)}function Xt(e,t){let n=-1;for(let i of this)e.call(t,i,++n,this);return this}function Yt(e,t){for(var n=this,i=[n],r,o,a=-1;n=i.pop();)if(e.call(t,n,++a,this),r=n.children)for(o=r.length-1;o>=0;--o)i.push(r[o]);return this}function $t(e,t){for(var n=this,i=[n],r=[],o,a,s,l=-1;n=i.pop();)if(r.push(n),o=n.children)for(a=0,s=o.length;a<s;++a)i.push(o[a]);for(;n=r.pop();)e.call(t,n,++l,this);return this}function Zt(e,t){let n=-1;for(let i of this)if(e.call(t,i,++n,this))return i}function jt(e){return this.eachAfter(function(t){for(var n=+e(t.data)||0,i=t.children,r=i&&i.length;--r>=0;)n+=i[r].value;t.value=n})}function Vt(e){return this.eachBefore(function(t){t.children&&t.children.sort(e)})}function Wt(e){for(var t=this,n=Mi(t,e),i=[t];t!==n;)t=t.parent,i.push(t);for(var r=i.length;e!==n;)i.splice(r,0,e),e=e.parent;return i}function Mi(e,t){if(e===t)return e;var n=e.ancestors(),i=t.ancestors(),r=null;for(e=n.pop(),t=i.pop();e===t;)r=e,e=n.pop(),t=i.pop();return r}function Kt(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t}function Qt(){return Array.from(this)}function Jt(){var e=[];return this.eachBefore(function(t){t.children||e.push(t)}),e}function en(){var e=this,t=[];return e.each(function(n){n!==e&&t.push({source:n.parent,target:n})}),t}function*tn(){var e=this,t,n=[e],i,r,o;do for(t=n.reverse(),n=[];e=t.pop();)if(yield e,i=e.children)for(r=0,o=i.length;r<o;++r)n.push(i[r]);while(n.length)}function Ae(e,t){e instanceof Map?(e=[void 0,e],t===void 0&&(t=Si)):t===void 0&&(t=_i);for(var n=new be(e),i,r=[n],o,a,s,l;i=r.pop();)if((a=t(i.data))&&(l=(a=Array.from(a)).length))for(i.children=a,s=l-1;s>=0;--s)r.push(o=a[s]=new be(a[s])),o.parent=i,o.depth=i.depth+1;return n.eachBefore(yt)}function wi(){return Ae(this).eachBefore(Ti)}function _i(e){return e.children}function Si(e){return Array.isArray(e)?e[1]:null}function Ti(e){e.data.value!==void 0&&(e.value=e.data.value),e.data=e.data.data}function yt(e){var t=0;do e.height=t;while((e=e.parent)&&e.height<++t)}function be(e){this.data=e,this.depth=this.height=0,this.parent=null}be.prototype=Ae.prototype={constructor:be,count:Ht,each:Xt,eachAfter:$t,eachBefore:Yt,find:Zt,sum:jt,sort:Vt,path:Wt,ancestors:Kt,descendants:Qt,leaves:Jt,links:en,copy:wi,[Symbol.iterator]:tn};function Qe(e){return e==null?null:Pi(e)}function Pi(e){if(typeof e!="function")throw new Error;return e}var Bi={depth:-1},nn={},vt={};function zi(e){return e.id}function Ci(e){return e.parentId}function bt(){var e=zi,t=Ci,n;function i(r){var o=Array.from(r),a=e,s=t,l,u,c,f,d,p,m,g,y=new Map;if(n!=null){let w=o.map((v,b)=>ki(n(v,b,r))),M=w.map(rn),h=new Set(w).add("");for(let v of M)h.has(v)||(h.add(v),w.push(v),M.push(rn(v)),o.push(vt));a=(v,b)=>w[b],s=(v,b)=>M[b]}for(c=0,l=o.length;c<l;++c)u=o[c],p=o[c]=new be(u),(m=a(u,c,r))!=null&&(m+="")&&(g=p.id=m,y.set(g,y.has(g)?nn:p)),(m=s(u,c,r))!=null&&(m+="")&&(p.parent=m);for(c=0;c<l;++c)if(p=o[c],m=p.parent){if(d=y.get(m),!d)throw new Error("missing: "+m);if(d===nn)throw new Error("ambiguous: "+m);d.children?d.children.push(p):d.children=[p],p.parent=d}else{if(f)throw new Error("multiple roots");f=p}if(!f)throw new Error("no root");if(n!=null){for(;f.data===vt&&f.children.length===1;)f=f.children[0],--l;for(let w=o.length-1;w>=0&&(p=o[w],p.data===vt);--w)p.data=null}if(f.parent=Bi,f.eachBefore(function(w){w.depth=w.parent.depth+1,--l}).eachBefore(yt),f.parent=null,l>0)throw new Error("cycle");return f}return i.id=function(r){return arguments.length?(e=Qe(r),i):e},i.parentId=function(r){return arguments.length?(t=Qe(r),i):t},i.path=function(r){return arguments.length?(n=Qe(r),i):n},i}function ki(e){e=`${e}`;let t=e.length;return xt(e,t-1)&&!xt(e,t-2)&&(e=e.slice(0,-1)),e[0]==="/"?e:`/${e}`}function rn(e){let t=e.length;if(t<2)return"";for(;--t>1&&!xt(e,t););return e.slice(0,t)}function xt(e,t){if(e[t]==="/"){let n=0;for(;t>0&&e[--t]==="\\";)++n;if((n&1)===0)return!0}return!1}function Ei(e,t){return e.parent===t.parent?1:2}function Mt(e){var t=e.children;return t?t[0]:e.t}function wt(e){var t=e.children;return t?t[t.length-1]:e.t}function Fi(e,t,n){var i=n/(t.i-e.i);t.c-=i,t.s+=n,e.c+=i,t.z+=n,t.m+=n}function Ii(e){for(var t=0,n=0,i=e.children,r=i.length,o;--r>=0;)o=i[r],o.z+=t,o.m+=t,t+=o.s+(n+=o.c)}function Di(e,t,n){return e.a.parent===t.parent?e.a:n}function Je(e,t){this._=e,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=t}Je.prototype=Object.create(be.prototype);function Ai(e){for(var t=new Je(e,0),n,i=[t],r,o,a,s;n=i.pop();)if(o=n._.children)for(n.children=new Array(s=o.length),a=s-1;a>=0;--a)i.push(r=n.children[a]=new Je(o[a],a)),r.parent=n;return(t.parent=new Je(null,0)).children=[t],t}function He(){var e=Ei,t=1,n=1,i=null;function r(u){var c=Ai(u);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),i)u.eachBefore(l);else{var f=u,d=u,p=u;u.eachBefore(function(M){M.x<f.x&&(f=M),M.x>d.x&&(d=M),M.depth>p.depth&&(p=M)});var m=f===d?1:e(f,d)/2,g=m-f.x,y=t/(d.x+m+g),w=n/(p.depth||1);u.eachBefore(function(M){M.x=(M.x+g)*y,M.y=M.depth*w})}return u}function o(u){var c=u.children,f=u.parent.children,d=u.i?f[u.i-1]:null;if(c){Ii(u);var p=(c[0].z+c[c.length-1].z)/2;d?(u.z=d.z+e(u._,d._),u.m=u.z-p):u.z=p}else d&&(u.z=d.z+e(u._,d._));u.parent.A=s(u,d,u.parent.A||f[0])}function a(u){u._.x=u.z+u.parent.m,u.m+=u.parent.m}function s(u,c,f){if(c){for(var d=u,p=u,m=c,g=d.parent.children[0],y=d.m,w=p.m,M=m.m,h=g.m,v;m=wt(m),d=Mt(d),m&&d;)g=Mt(g),p=wt(p),p.a=u,v=m.z+M-d.z-y+e(m._,d._),v>0&&(Fi(Di(m,u,f),u,v),y+=v,w+=v),M+=m.m,y+=d.m,h+=g.m,w+=p.m;m&&!wt(p)&&(p.t=m,p.m+=M-w),d&&!Mt(g)&&(g.t=d,g.m+=y-h,f=u)}return f}function l(u){u.x*=t,u.y=u.depth*n}return r.separation=function(u){return arguments.length?(e=u,r):e},r.size=function(u){return arguments.length?(i=!1,t=+u[0],n=+u[1],r):i?null:[t,n]},r.nodeSize=function(u){return arguments.length?(i=!0,t=+u[0],n=+u[1],r):i?[t,n]:null},r}var Le=pe(require("lodash"),1);var Ri={value:()=>{}};function sn(){for(var e=0,t=arguments.length,n={},i;e<t;++e){if(!(i=arguments[e]+"")||i in n||/[\s.]/.test(i))throw new Error("illegal type: "+i);n[i]=[]}return new et(n)}function et(e){this._=e}function Ui(e,t){return e.trim().split(/^|\s+/).map(function(n){var i="",r=n.indexOf(".");if(r>=0&&(i=n.slice(r+1),n=n.slice(0,r)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:i}})}et.prototype=sn.prototype={constructor:et,on:function(e,t){var n=this._,i=Ui(e+"",n),r,o=-1,a=i.length;if(arguments.length<2){for(;++o<a;)if((r=(e=i[o]).type)&&(r=Li(n[r],e.name)))return r;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<a;)if(r=(e=i[o]).type)n[r]=on(n[r],e.name,t);else if(t==null)for(r in n)n[r]=on(n[r],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new et(e)},call:function(e,t){if((r=arguments.length-2)>0)for(var n=new Array(r),i=0,r,o;i<r;++i)n[i]=arguments[i+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],i=0,r=o.length;i<r;++i)o[i].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var i=this._[e],r=0,o=i.length;r<o;++r)i[r].value.apply(t,n)}};function Li(e,t){for(var n=0,i=e.length,r;n<i;++n)if((r=e[n]).name===t)return r.value}function on(e,t,n){for(var i=0,r=e.length;i<r;++i)if(e[i].name===t){e[i]=Ri,e=e.slice(0,i).concat(e.slice(i+1));break}return n!=null&&e.push({name:t,value:n}),e}var _t=sn;var Re=0,Ye=0,Xe=0,un=1e3,tt,$e,nt=0,ze=0,it=0,Ze=typeof performance=="object"&&performance.now?performance:Date,cn=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Pt(){return ze||(cn(Gi),ze=Ze.now()+it)}function Gi(){ze=0}function St(){this._call=this._time=this._next=null}St.prototype=rt.prototype={constructor:St,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Pt():+n)+(t==null?0:+t),!this._next&&$e!==this&&($e?$e._next=this:tt=this,$e=this),this._call=e,this._time=n,Tt()},stop:function(){this._call&&(this._call=null,this._time=1/0,Tt())}};function rt(e,t,n){var i=new St;return i.restart(e,t,n),i}function dn(){Pt(),++Re;for(var e=tt,t;e;)(t=ze-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Re}function ln(){ze=(nt=Ze.now())+it,Re=Ye=0;try{dn()}finally{Re=0,qi(),ze=0}}function Ni(){var e=Ze.now(),t=e-nt;t>un&&(it-=t,nt=e)}function qi(){for(var e,t=tt,n,i=1/0;t;)t._call?(i>t._time&&(i=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:tt=n);$e=e,Tt(i)}function Tt(e){if(!Re){Ye&&(Ye=clearTimeout(Ye));var t=e-ze;t>24?(e<1/0&&(Ye=setTimeout(ln,e-Ze.now()-it)),Xe&&(Xe=clearInterval(Xe))):(Xe||(nt=Ze.now(),Xe=setInterval(Ni,un)),Re=1,cn(ln))}}function Me(e){let t=0,n=0,i=0,r=0;for(let[,o]of e)t+=o[0],n+=o[1],i+=o[2],r++;return r===0?[0,0,0]:[t/r,n/r,i/r]}var Se=1;function xe(e,t){let n=new Map;for(let i=0;i<e.nodes.length;i++)n.set(e.nodes[i].id,t[i]);return{positions:n}}function pn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=Me(e.positions),r=t?.spacing??Se,o=t?.radius??Math.max(r,n*r/(2*Math.PI)),a=Math.PI*2/n,s=[];for(let l=0;l<n;l++)s.push([o*Math.cos(l*a)+i[0],o*Math.sin(l*a)+i[1],0]);return xe(e,s)}function hn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=Me(e.positions),r=t?.columns&&t.columns>0?t.columns:Math.ceil(Math.sqrt(n)),o=t?.spacing??Se,a=o*(r-1),s=[];for(let l=0;l<n;l++)s.push([l%r*o-a/2+i[0],-Math.floor(l/r)*o+a/2+i[1],0]);return xe(e,s)}function mn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=Me(e.positions),r=t?.axis??"x",o=t?.spacing??Se,a=o*(n-1),s=[];for(let l=0;l<n;l++){let u=n>1?-a/2+l*o:0,c=[i[0],i[1],i[2]],f=r==="x"?0:r==="y"?1:2;c[f]=u+i[f],s.push(c)}return xe(e,s)}function gn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=Me(e.positions),r=t?.spacing??1.5,o=r/(2*Math.PI),a=2*Math.PI,s=[];for(let l=0;l<n;l++){let u=o*a;s.push([u*Math.cos(a)+i[0],u*Math.sin(a)+i[1],0]),a+=r/u}return xe(e,s)}function yn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=Me(e.positions),r=Math.cbrt(n),o=Math.floor(r),a=Math.ceil(r),s=t?.size??(n-Math.pow(o,3)>Math.pow(a,3)-n?a:o),l=t?.spacing??Se,u=l*Math.max(s-1,0),c=[];for(let f=0;f<n;f++)c.push([f%s*l-u/2+i[0],-(Math.floor(f/s)%s)*l+u/2+i[1],-Math.floor(f/(s*s))*l+u/2+i[2]]);return xe(e,c)}function vn(e,t){let n=e.nodes.length;if(n<=1){let l=new Map;return n===1&&l.set(e.nodes[0].id,e.positions.get(e.nodes[0].id)??[0,0,0]),{positions:l}}let i=Me(e.positions),r=t?.spacing??Se,o=t?.density!==void 0?Math.sqrt(n/(4*Math.PI*t.density)):r*Math.sqrt(n/(4*Math.PI)),a=t?.radius??Math.max(r,o),s=[];for(let l=0;l<n;l++){let u=Math.acos(1-(2*(l+1)-1)/n),c=Math.sqrt(n*Math.PI)*u;s.push([a*Math.sin(u)*Math.cos(c)+i[0],a*Math.sin(u)*Math.sin(c)+i[1],a*Math.cos(u)+i[2]])}return xe(e,s)}function xn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=t?.spacing??Se,r=t?.range??Math.max(i,i*Math.cbrt(n)/2),o=t?.seed??42;function a(){o|=0,o=o+1831565813|0;let l=Math.imul(o^o>>>15,1|o);return l=l+Math.imul(l^l>>>7,61|l)^l,((l^l>>>14)>>>0)/4294967296}let s=[];for(let l=0;l<n;l++)s.push([(a()-.5)*r*2,(a()-.5)*r*2,(a()-.5)*r*2]);return xe(e,s)}function bn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.axis??"x",r=(t?.degrees??90)*Math.PI/180,o=Me(e.positions),a=[];for(let s of e.nodes){let l=e.positions.get(s.id)??[0,0,0],u=l[0]-o[0],c=l[1]-o[1],f=l[2]-o[2],d,p,m,g=Math.cos(r),y=Math.sin(r);i==="x"?(d=u,p=c*g-f*y,m=c*y+f*g):i==="y"?(d=u*g+f*y,p=c,m=-u*y+f*g):(d=u*g-c*y,p=u*y+c*g,m=f),a.push([d+o[0],p+o[1],m+o[2]])}return xe(e,a)}function Mn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.factor,r=i??t?.x??1,o=i??t?.y??1,a=i??t?.z??1,s=Me(e.positions),l=[];for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0];l.push([c[0]+(c[0]-s[0])*(r-1),c[1]+(c[1]-s[1])*(o-1),c[2]+(c[2]-s[2])*(a-1)])}return xe(e,l)}function wn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.x??0,r=t?.y??0,o=t?.z??0,a=[];for(let s of e.nodes){let l=e.positions.get(s.id)??[0,0,0];a.push([l[0]+i,l[1]+r,l[2]+o])}return xe(e,a)}function _n(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.axis??"x",r=i==="x"?0:i==="y"?1:2,o=1/0,a=-1/0;for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0];c[r]<o&&(o=c[r]),c[r]>a&&(a=c[r])}let s=(o+a)/2,l=[];for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0],f=[c[0],c[1],c[2]];f[r]=s,l.push(f)}return xe(e,l)}function Sn(e,t){let{depth:n=100,mode:i="tree",orientation:r="right",alongRelationships:o=[]}=t??{},a=t?.spacing??Se,s=t?.spacing===void 0?t?.edgeLength:void 0,l=e.nodes;if(l.length===0)return{positions:new Map};let u=new Set;for(let[x]of e.positions)u.add(x);let c=new Map,f=new Map;for(let x of e.edges)!u.has(x.source)||!u.has(x.target)||(f.set(x.id,x),c.has(x.source)||c.set(x.source,[]),c.has(x.target)||c.set(x.target,[]),c.get(x.source).push({nodeId:x.target,relationship:x.relationship}),c.get(x.target).push({nodeId:x.source,relationship:x.relationship}));let d=o.length>0?new Set(Array.from(c.entries()).filter(([,x])=>x.some(({relationship:C})=>o.includes(C))).map(([x])=>x)):u,p=l.filter(x=>d.has(x.id));if(p.length===0)return{positions:new Map};let m=new Map,g=p.map(x=>[{from:"",to:x.id}]),y=p.map(x=>[[x.id]]),w=p.map(()=>1),M=p.map(()=>[1]),h=p.map(x=>x.id),v=1;for(;v<=n&&Le.sum(y.map(x=>x[v-1]?.length??0))>0;)y.forEach((x,C)=>{let E=x[v-1];if(!E)return;let A=[];E.forEach(R=>{let I=c.get(R)??[],L=I.map(({nodeId:B})=>B);o.length>0&&(L=I.filter(({relationship:B})=>o.includes(B)).map(({nodeId:B})=>B)),L=Le.difference(Le.intersection(L,Array.from(d)),h),L.forEach(B=>{g[C].push({from:R,to:B}),A.push(B),h.push(B)})}),x[v]=A,A.length>0&&(M[C].push(A.length),w[C]++)}),v++;let b=bt().id(x=>x.to).parentId(x=>x.from||null);return p.forEach((x,C)=>{let E=e.positions.get(x.id)??[0,0,0];if(g[C].length<=1){m.set(x.id,[E[0],E[1],E[2]]);return}let A;try{A=b(g[C])}catch{m.set(x.id,[E[0],E[1],E[2]]);return}let R=Math.max(...M[C],1),I=Math.max(w[C]-1,1),L=Math.max(R-1,1),B,F;i==="rings"?(B=2*Math.PI,s!==void 0?F=s*I:F=Math.max(a,a*R/(2*Math.PI))):s!==void 0?(B=s*R*.2*Math.pow(w[C],.3),F=s*I):(B=a*L,F=a*I);let z=He().size([B,F])(A);Tn(i,r,z,z,E,m)}),{positions:m}}function Tn(e,t,n,i,r,o){let a=i.id,s,l;if(e==="tree")switch(t){case"up":s=i.x+r[0]-n.x,l=i.y+r[1]+n.y;break;case"down":s=-i.x+r[0]+n.x,l=-i.y+r[1]-n.y;break;case"right":s=i.y+r[0]-n.y,l=-i.x+r[1]+n.x;break;case"left":s=-i.y+r[0]+n.y,l=i.x+r[1]-n.x;break}else switch(t){case"down":s=r[0]+i.y*Math.cos(i.x+Math.PI/2),l=r[1]+i.y*Math.sin(i.x+Math.PI/2);break;case"up":s=r[0]+i.y*Math.cos(i.x+3*Math.PI/2),l=r[1]+i.y*Math.sin(i.x+3*Math.PI/2);break;case"right":s=r[0]+i.y*Math.cos(i.x+Math.PI),l=r[1]+i.y*Math.sin(i.x+Math.PI);break;case"left":s=r[0]+i.y*Math.cos(i.x),l=r[1]+i.y*Math.sin(i.x);break}if(o.set(a,[s,l,r[2]]),i.children)for(let u of i.children)Tn(e,t,n,u,r,o)}var ot=1.5,zt=3;function at(e,t){return t==="category"?e.category:e.properties?.[t]}function st(e,t,n){let i=n&&n.length?new Set(n):null,r=new Set,o=[],a=e.size;for(let s of t){if(i&&!i.has(s.relationship))continue;let l=e.get(s.source),u=e.get(s.target);if(l===void 0||u===void 0||l===u)continue;let c=l*a+u;r.has(c)||(r.add(c),o.push([l,u]))}return o}function Pn(e,t){let n=[],i=new Set;for(let r of e)r!=null&&!i.has(r)&&(i.add(r),n.push(r));if(t){let r=t.filter(a=>i.has(a)),o=new Set(r);return[...r,...n.filter(a=>!o.has(a))]}return n.every(r=>typeof r=="number")?[...n].sort((r,o)=>r-o):n}function Ct(e,t,n){switch(e){case"BT":return[n,t];case"LR":return[t,-n];case"RL":return[-t,-n];default:return[n,-t]}}function lt(e,t){if(t.size===0)return t;let n=0,i=0,r=0;for(let f of e.nodes){let d=e.positions.get(f.id);d&&(n+=d[0],i+=d[1],r++)}r&&(n/=r,i/=r);let o=1/0,a=-1/0,s=1/0,l=-1/0;for(let f of t.values())f[0]<o&&(o=f[0]),f[0]>a&&(a=f[0]),f[1]<s&&(s=f[1]),f[1]>l&&(l=f[1]);let u=n-(o+a)/2,c=i-(s+l)/2;for(let f of t.values())f[0]+=u,f[1]+=c;return t}function Bn(e,t,n){let i=e.length,r=Array.from({length:i},()=>[]),o=new Int32Array(i);for(let[c,f]of t)r[c].push(f),o[f]++;let a;if(n&&n.length){let c=new Set(n);a=[],e.forEach((f,d)=>{c.has(f.id)&&a.push(d)})}else{a=[];for(let c=0;c<i;c++)o[c]===0&&a.push(c);if(!a.length&&i){let c=0;for(let f=1;f<i;f++)r[f].length>r[c].length&&(c=f);a.push(c)}}let s=Array.from({length:i},()=>[]),l=new Uint8Array(i),u=c=>{l[c]=1;let f=[c];for(let d=0;d<f.length;d++){let p=f[d];for(let m of r[p])l[m]||(l[m]=1,s[p].push(m),f.push(m))}};for(let c of a)l[c]||u(c);for(let c=0;c<2;c++)for(let f=0;f<i;f++)l[f]||c===0&&o[f]>0||(a.push(f),u(f));return{roots:a.filter((c,f)=>a.indexOf(c)===f),children:s}}function zn(e,t){let n=e.children.length,i=u=>({i:u,children:[]}),r={i:-1,children:[]},o=[];for(let u of e.roots){let c=i(u);r.children.push(c),o.push(c)}for(;o.length;){let u=o.pop();for(let c of e.children[u.i]){let f=i(c);u.children.push(f),o.push(f)}}let a=Ae(r,u=>u.children);He().nodeSize([t,1]).separation((u,c)=>u.parent===c.parent?1:1.5)(a);let s=new Int32Array(n),l=new Float64Array(n);return a.each(u=>{u.data.i<0||(s[u.data.i]=u.depth-1,l[u.data.i]=u.x)}),{depth:s,across:l}}function Cn(e,t={}){let n=e.nodes,i=new Map(n.map((f,d)=>[f.id,d])),r=Bn(n,st(i,e.edges,t.relationships),t.roots),o=t.nodeGap??ot,a=t.levelGap??zt,s=t.direction??"TB",{depth:l,across:u}=zn(r,o),c=new Map;return n.forEach((f,d)=>{let[p,m]=Ct(s,l[d]*a,u[d]);c.set(f.id,[p,m,0])}),{positions:lt(e,c)}}function kn(e,t={}){let n=e.nodes,i=new Map(n.map((h,v)=>[h.id,v])),r=Bn(n,st(i,e.edges,t.relationships),t.roots),o=t.nodeGap??ot,a=t.levelGap??zt,s=(t.sweep??360)*Math.PI/180,l=(t.startAngle??90)*Math.PI/180,{depth:u,across:c}=zn(r,o),f=r.roots.length===1,d=1/0,p=-1/0,m=0;for(let h=0;h<n.length;h++)c[h]<d&&(d=c[h]),c[h]>p&&(p=c[h]),u[h]>m&&(m=u[h]);let g=Math.abs(s-2*Math.PI)<1e-6,y=Math.max(p-d+(g?o:0),1e-9),w=Math.max(a,y/s/Math.max(m+(f?0:1),1)),M=new Map;return n.forEach((h,v)=>{let b=(u[v]+(f?0:1))*w,x=l-(c[v]-d)/y*s;M.set(h.id,[b*Math.cos(x),b*Math.sin(x),0])}),{positions:lt(e,M)}}function Oi(e){if(e.length<2)return 0;let t=e.slice(),n=new Array(t.length),i=0;for(let r=1;r<t.length;r*=2)for(let o=0;o<t.length-r;o+=2*r){let a=o+r,s=Math.min(o+2*r,t.length),l=o,u=a,c=o;for(;l<a&&u<s;)t[l]<=t[u]?n[c++]=t[l++]:(n[c++]=t[u++],i+=a-l);for(;l<a;)n[c++]=t[l++];for(;u<s;)n[c++]=t[u++];for(let f=o;f<s;f++)t[f]=n[f]}return i}function Hi(e,t){let n=e.length,i=new Array(n);i[0]=0;for(let l=1;l<n;l++)i[l]=i[l-1]+t[l-1];let r=[],o=[];for(let l=0;l<n;l++)for(r.push(e[l]-i[l]),o.push(1);r.length>1&&r[r.length-2]/o[o.length-2]>r[r.length-1]/o[o.length-1];){let u=r.pop(),c=o.pop();r[r.length-1]+=u,o[o.length-1]+=c}let a=new Array(n),s=0;for(let l=0;l<r.length;l++){let u=r[l]/o[l];for(let c=0;c<o[l];c++,s++)a[s]=u+i[s]}return a}function Xi(e,t){let n=Array.from({length:e},()=>[]);t.forEach(([d,p],m)=>n[d].push(m));let i=new Uint8Array(e),r=new Uint8Array(t.length);for(let d=0;d<e;d++){if(i[d])continue;let p=[[d,0]];for(i[d]=1;p.length;){let m=p[p.length-1],[g,y]=m;if(y<n[g].length){m[1]++;let w=n[g][y],M=t[w][1];i[M]===1?r[w]=1:i[M]===0&&(i[M]=1,p.push([M,0]))}else i[g]=2,p.pop()}}let o=t.map(([d,p],m)=>r[m]?[p,d]:[d,p]),a=Array.from({length:e},()=>[]),s=Array.from({length:e},()=>[]),l=new Int32Array(e);for(let[d,p]of o)a[d].push(p),s[p].push(d),l[p]++;let u=[];for(let d=0;d<e;d++)l[d]===0&&u.push(d);for(let d=0;d<u.length;d++)for(let p of a[u[d]])--l[p]===0&&u.push(p);let c=new Array(e).fill(0);for(let d of u)for(let p of a[d])c[p]=Math.max(c[p],c[d]+1);for(let d=u.length-1;d>=0;d--){let p=u[d];if(s[p].length||!a[p].length)continue;let m=1/0;for(let g of a[p])m=Math.min(m,c[g]);c[p]=m-1}let f=Math.min(...c);return{rank:c.map(d=>d-f),dag:o}}function Yi(e,t,n){let i=t.slice(),r=new Array(e).fill(!1),o=Array.from({length:e},()=>[]),a=Array.from({length:e},()=>[]),s=(d,p)=>{a[d].push(p),o[p].push(d)};for(let[d,p]of n){if(i[p]-i[d]<1)continue;let m=d;for(let g=i[d]+1;g<i[p];g++){let y=i.length;i.push(g),r.push(!0),o.push([]),a.push([]),s(m,y),m=y}s(m,p)}let l=i.reduce((d,p)=>Math.max(d,p),0),u=Array.from({length:l+1},()=>[]),c=new Uint8Array(i.length),f=d=>{let p=[d];for(;p.length;){let m=p.pop();if(!c[m]){c[m]=1,u[i[m]].push(m);for(let g=a[m].length-1;g>=0;g--)c[a[m][g]]||p.push(a[m][g])}}};for(let d=0;d<e;d++)o[d].length||f(d);for(let d=0;d<i.length;d++)c[d]||f(d);return{rank:i,isDummy:r,up:o,down:a,layers:u}}function fn(e,t){let n=0;for(let i=0;i+1<e.layers.length;i++){let r=[];for(let o of e.layers[i])for(let a of e.down[o])r.push([t[o],t[a]]);r.sort((o,a)=>o[0]-a[0]||o[1]-a[1]),n+=Oi(r.map(o=>o[1]))}return n}function $i(e,t){let n=new Int32Array(e.rank.length);(()=>{for(let a of e.layers)a.forEach((s,l)=>{n[s]=l})})();let r=fn(e,n),o=e.layers.map(a=>a.slice());for(let a=0;a<t&&r>0;a++){let s=a%2===0,l=s?Array.from({length:e.layers.length-1},(c,f)=>f+1):Array.from({length:e.layers.length-1},(c,f)=>e.layers.length-2-f);for(let c of l){let f=e.layers[c],d=new Map;for(let p of f){let m=s?e.up[p]:e.down[p];d.set(p,m.length?m.reduce((g,y)=>g+n[y],0)/m.length:n[p])}f.sort((p,m)=>d.get(p)-d.get(m)||n[p]-n[m]),f.forEach((p,m)=>{n[p]=m})}let u=fn(e,n);u<r&&(r=u,o=e.layers.map(c=>c.slice()))}e.layers=o}function Zi(e,t){let n=new Float64Array(e.rank.length),i=(a,s)=>t*((e.isDummy[a]?.4:1)+(e.isDummy[s]?.4:1))/2,r=a=>a.slice(1).map((s,l)=>i(a[l],s));for(let a of e.layers){let s=r(a),l=0,u=[0];for(let c of s)u.push(l+=c);a.forEach((c,f)=>{n[c]=u[f]-l/2})}let o=a=>a.reduce((s,l)=>s+n[l],0)/a.length;for(let a=0;a<8;a++){let s=a%2===0,l=e.layers.map((u,c)=>s?c:e.layers.length-1-c);for(let u of l){let c=e.layers[u];if(!c.length)continue;let f=c.map(p=>{let m=e.isDummy[p]||a===7?[...e.up[p],...e.down[p]]:s?e.up[p]:e.down[p];return m.length?o(m):n[p]}),d=Hi(f,r(c));c.forEach((p,m)=>{n[p]=d[m]})}}return n}function En(e,t={}){let n=e.nodes,i=n.length;if(!i)return{positions:new Map};let r=new Map(n.map((p,m)=>[p.id,m])),o=st(r,e.edges,t.relationships),a,s;if(t.rankBy){let p=n.map(y=>at(y,t.rankBy)),m=Pn(p,t.rankOrder),g=new Map(m.map((y,w)=>[y,w]));a=p.map(y=>g.get(y)??m.length),s=o.map(([y,w])=>a[y]<=a[w]?[y,w]:[w,y])}else({rank:a,dag:s}=Xi(i,o));let l=Yi(i,a,s);$i(l,t.sweeps??24);let u=Zi(l,t.nodeGap??ot),c=t.levelGap??zt,f=t.direction??"TB",d=new Map;return n.forEach((p,m)=>{let[g,y]=Ct(f,l.rank[m]*c,u[m]);d.set(p.id,[g,y,0])}),{positions:lt(e,d)}}function Fn(e,t){let n=e.nodes;if(!n.length)return{positions:new Map};if(!t||!t.by)throw new Error("[columnsLayout] option `by` is required");let i=new Map(n.map((M,h)=>[M.id,h])),r=n.map(M=>at(M,t.by)),o=Pn(r,t.order),a=new Map(o.map((M,h)=>[M,h])),s=r.map(M=>a.get(M)??o.length),l=Math.max(...s)+1,u=Array.from({length:l},()=>[]);n.forEach((M,h)=>u[s[h]].push(h));let c=n.map(()=>[]);for(let[M,h]of st(i,e.edges,t.relationships))s[M]!==s[h]&&(c[M].push(h),c[h].push(M));let f=t.sortBy??"barycenter",d=new Float64Array(n.length),p=M=>M.forEach((h,v)=>{d[h]=v-(M.length-1)/2});if(u.forEach(p),f==="barycenter")for(let M=0;M<12;M++){let h=u.map((v,b)=>M%2===0?b:l-1-b);for(let v of h){let b=u[v],x=new Map(b.map(C=>[C,c[C].length?c[C].reduce((E,A)=>E+d[A],0)/c[C].length:d[C]]));b.sort((C,E)=>x.get(C)-x.get(E)||d[C]-d[E]),p(b)}}else if(f==="degree")for(let M of u)M.sort((h,v)=>c[v].length-c[h].length||h-v),p(M);else if(f!=="none")for(let M of u)M.sort((h,v)=>{let b=at(n[h],f),x=at(n[v],f);return typeof b=="number"&&typeof x=="number"?b-x||h-v:String(b??"").localeCompare(String(x??""))||h-v}),p(M);let m=t.nodeGap??ot,g=t.levelGap??4,y=t.direction??"LR",w=new Map;return n.forEach((M,h)=>{let[v,b]=Ct(y,s[h]*g,d[h]*m);w.set(M.id,[v,b,0])}),{positions:lt(e,w)}}function _e(e){if(e==null)return null;let t=Number(e);return Number.isNaN(t)?null:t}function Ce(e,t,n){let[i,r]=t,[o,a]=n;return r===i?(o+a)/2:o+(e-i)/(r-i)*(a-o)}function ke(e,t,n){let i=Math.max(t[0],1e-10),r=Math.max(t[1],1e-10),o=Math.max(e,1e-10),[a,s]=n;return r===i?(a+s)/2:a+(Math.log(o)-Math.log(i))/(Math.log(r)-Math.log(i))*(s-a)}function In(e,t,n){let i=n??_e,r=1/0,o=-1/0;for(let a of e){let s=a.properties?.[t],l=i(s);l!=null&&(l<r&&(r=l),l>o&&(o=l))}return r===1/0?[0,1]:r===o?[r-1,o+1]:[r,o]}function Dn(e,t=5){let[n,i]=e,r=i-n;if(r===0)return[n-1,i+1];let o=r/t,a=Math.pow(10,Math.floor(Math.log10(o))),s=o/a,l;return s<=1.5?l=a:s<=3.5?l=2*a:s<=7.5?l=5*a:l=10*a,[Math.floor(n/l)*l,Math.ceil(i/l)*l]}function An(e,t=5){let[n,i]=e;if(n===i)return[n];let o=(i-n)/t,a=Math.pow(10,Math.floor(Math.log10(o))),s=o/a,l;s<=1.5?l=a:s<=3.5?l=2*a:s<=7.5?l=5*a:l=10*a;let u=Math.ceil(n/l)*l,c=[];for(let f=u;f<=i+l*.001;f+=l)c.push(Math.round(f*1e10)/1e10);return c}var Bt=[{name:"1s",ms:1e3},{name:"5s",ms:5e3},{name:"15s",ms:15e3},{name:"30s",ms:3e4},{name:"1m",ms:6e4},{name:"5m",ms:3e5},{name:"15m",ms:9e5},{name:"30m",ms:18e5},{name:"1h",ms:36e5},{name:"3h",ms:108e5},{name:"6h",ms:216e5},{name:"12h",ms:432e5},{name:"1d",ms:864e5},{name:"3d",ms:2592e5},{name:"1w",ms:6048e5},{name:"1mo",ms:2592e6,calendarUnit:"month",calendarStep:1},{name:"3mo",ms:7776e6,calendarUnit:"month",calendarStep:3},{name:"6mo",ms:15552e6,calendarUnit:"month",calendarStep:6},{name:"1y",ms:31536e6,calendarUnit:"year",calendarStep:1},{name:"2y",ms:63072e6,calendarUnit:"year",calendarStep:2},{name:"5y",ms:15768e7,calendarUnit:"year",calendarStep:5},{name:"10y",ms:31536e7,calendarUnit:"year",calendarStep:10},{name:"20y",ms:63072e7,calendarUnit:"year",calendarStep:20},{name:"50y",ms:15768e8,calendarUnit:"year",calendarStep:50}];function Rn(e,t=5){let[n,i]=e,r=i-n;if(r<=0)return[n];let o=r/t,a=Bt[Bt.length-1];for(let l of Bt)if(l.ms>=o*.6){a=l;break}let s=[];if(a.calendarUnit==="year"){let l=a.calendarStep,u=new Date(n),c=Math.ceil(u.getFullYear()/l)*l;for(;;){let f=new Date(c,0,1).getTime();if(f>i)break;f>=n&&s.push(f),c+=l}}else if(a.calendarUnit==="month"){let l=a.calendarStep,u=new Date(n),c=u.getFullYear(),f=Math.ceil(u.getMonth()/l)*l;for(;;){let d=new Date(c,f,1).getTime();if(d>i)break;d>=n&&s.push(d),f+=l,f>=12&&(c+=Math.floor(f/12),f=f%12)}}else{let l=a.ms,u=Math.ceil(n/l)*l;for(let c=u;c<=i;c+=l)s.push(c)}return s}function Un(e,t){let n=t[1]-t[0],i=new Date(e);return n>365*864e5*2?String(i.getFullYear()):n>60*864e5?`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}`:n>2*864e5?`${i.getMonth()+1}/${i.getDate()}`:n>2*36e5?`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`:`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}:${String(i.getSeconds()).padStart(2,"0")}`}function Ue(e,t,n){let i=e.domain??In(t,e.property,e.parse);e.nice&&!e.domain&&(i=Dn(i,e.tickCount));let o=(i[1]-i[0])*n,a=[i[0]-o,i[1]+o],s;e.tickValues?s=e.tickValues:e.isDate?s=Rn(i,e.tickCount):s=An(i,e.tickCount);let l=e.tickFormat;return!l&&e.isDate&&(l=u=>Un(u,i)),{axisInfo:{property:e.property,label:e.property,domain:a,ticks:s,scale:e.scale,tickFormat:l},paddedDomain:a}}function Ln(e,t){let{propertyX:n,propertyY:i,propertyZ:r,range:o=[-2,2],scaleX:a="linear",scaleY:s="linear",scaleZ:l="linear",padding:u=.05}=t,c=t.parseX??_e,f=t.parseY??_e,d=t.parseZ??_e,p=!!n,m=!!i,g=!!r,y=e.nodes,w=new Map,M=new Set,h=[];for(let B of y){let F=0,_=0,z=0,P=!1;if(p){let T=c(B.properties?.[n]);T==null?P=!0:F=T}if(m&&!P){let T=f(B.properties?.[i]);T==null?P=!0:_=T}if(g&&!P){let T=d(B.properties?.[r]);T==null?P=!0:z=T}P?M.add(B.id):h.push({id:B.id,x:F,y:_,z})}let v=p?Ue({property:n,scale:a,domain:t.domainX,parse:c,tickFormat:t.tickFormatX,tickCount:t.tickCountX??5,tickValues:t.tickValuesX,nice:t.niceX??!0,isDate:t.dateAxisX??!1},y,u):null,b=m?Ue({property:i,scale:s,domain:t.domainY,parse:f,tickFormat:t.tickFormatY,tickCount:t.tickCountY??5,tickValues:t.tickValuesY,nice:t.niceY??!0,isDate:t.dateAxisY??!1},y,u):null,x=g?Ue({property:r,scale:l,domain:t.domainZ,parse:d,tickFormat:t.tickFormatZ,tickCount:t.tickCountZ??5,tickValues:t.tickValuesZ,nice:t.niceZ??!0,isDate:t.dateAxisZ??!1},y,u):null,C=a==="log"?ke:Ce,E=s==="log"?ke:Ce,A=l==="log"?ke:Ce,R=t.spread??1,I=[o[0]*R,o[1]*R],L=o[0];for(let B of h){let F=v?C(B.x,v.paddedDomain,I):L,_=b?E(B.y,b.paddedDomain,I):L,z=x?A(B.z,x.paddedDomain,I):0;w.set(B.id,[F,_,z])}return{positions:w,axes:{x:v?.axisInfo,y:b?.axisInfo,z:x?.axisInfo},range:I,baseRange:o,excludedNodeIds:M}}function Gn(e,t){let n=t.range??[-2,2],i=t.spread??1,r=[n[0]*i,n[1]*i],o=t.padding??.05,a=n[0],s=t.unmappedMode??"hide",l=new Map;for(let p of t.mappings)l.set(p.category,p);let u=new Map;for(let p of e.nodes){let m=p.category,g=u.get(m);g||(g=[],u.set(m,g)),g.push(p)}let c=new Map,f=new Set,d={};for(let[p,m]of u){let g=l.get(p);if(!g){if(s==="hide")for(let G of m)f.add(G.id);else{let G;s==="boundary"?G=n[0]:G=(n[0]+n[1])/2;for(let S of m)c.set(S.id,[G,G,0])}continue}let y=!!g.propertyX,w=!!g.propertyY,M=!!g.propertyZ,h=g.scaleX??"linear",v=g.scaleY??"linear",b=g.scaleZ??"linear",x=g.parseX??_e,C=g.parseY??_e,E=g.parseZ??_e,A=g.tickCountX??t.tickCountX??5,R=g.tickCountY??t.tickCountY??5,I=g.tickCountZ??t.tickCountZ??5,L=g.niceX??t.niceX??!0,B=g.niceY??t.niceY??!0,F=g.niceZ??t.niceZ??!0,_=[];for(let G of m){let S=0,D=0,O=0,Y=!1;if(y){let X=x(G.properties?.[g.propertyX]);X==null?Y=!0:S=X}if(w&&!Y){let X=C(G.properties?.[g.propertyY]);X==null?Y=!0:D=X}if(M&&!Y){let X=E(G.properties?.[g.propertyZ]);X==null?Y=!0:O=X}Y?f.add(G.id):_.push({id:G.id,x:S,y:D,z:O})}let z=y?Ue({property:g.propertyX,scale:h,domain:g.domainX,parse:x,tickFormat:g.tickFormatX,tickCount:A,tickValues:g.tickValuesX,nice:L,isDate:g.dateAxisX??!1},m,o):null,P=w?Ue({property:g.propertyY,scale:v,domain:g.domainY,parse:C,tickFormat:g.tickFormatY,tickCount:R,tickValues:g.tickValuesY,nice:B,isDate:g.dateAxisY??!1},m,o):null,T=M?Ue({property:g.propertyZ,scale:b,domain:g.domainZ,parse:E,tickFormat:g.tickFormatZ,tickCount:I,tickValues:g.tickValuesZ,nice:F,isDate:g.dateAxisZ??!1},m,o):null,k=h==="log"?ke:Ce,q=v==="log"?ke:Ce,N=b==="log"?ke:Ce;for(let G of _){let S=z?k(G.x,z.paddedDomain,r):a,D=P?q(G.y,P.paddedDomain,r):a,O=T?N(G.z,T.paddedDomain,r):0;c.set(G.id,[S,D,O])}d[p]={x:z?.axisInfo,y:P?.axisInfo,z:T?.axisInfo}}return{positions:c,axes:{x:void 0,y:void 0,z:void 0},range:r,baseRange:n,excludedNodeIds:f,categoryAxes:d}}var ji=/^[a-z][a-zA-Z0-9]*$/,Vi=/^[a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9_-]*$/,Nn=class qn{constructor(){this.entries=new Map}register(t,n,i={}){if(!Vi.test(t))throw new Error(`[LayoutRegistry] invalid layout name "${t}": extension layouts must be named "<pack>:<name>" (e.g. "acme:rack")`);return this.add(t,n,!1,i)}registerBuiltin(t,n,i){if(!ji.test(t))throw new Error(`[LayoutRegistry] invalid built-in layout name "${t}"`);this.add(t,n,!0,{description:i})}add(t,n,i,r){if(typeof n!="function")throw new Error(`[LayoutRegistry] layout "${t}" must be a function`);let o=this.entries.get(t);if(o&&(o.builtin||!r.replace))throw new Error(`[LayoutRegistry] layout "${t}" is already registered`);let a={name:t,fn:n,builtin:i,description:r.description};return this.entries.set(t,a),()=>{this.entries.get(t)===a&&this.entries.delete(t)}}has(t){return this.entries.has(t)}get(t){return this.entries.get(t)}list(){let t=[...this.entries.values()];return[...t.filter(n=>n.builtin),...t.filter(n=>!n.builtin)]}execute(t,n,i){let r=this.entries.get(t);if(!r)throw new Error(`[LayoutRegistry] unknown layout "${t}". Registered: ${[...this.entries.keys()].join(", ")}`);return r.fn(n,i)}fork(){let t=new qn;for(let[n,i]of this.entries)t.entries.set(n,i);return t}};function Wi(){let e=new Nn;return e.registerBuiltin("circle",pn,"Nodes on a circle."),e.registerBuiltin("grid",hn,"Nodes on a 2-D grid."),e.registerBuiltin("line",mn,"Nodes along an axis."),e.registerBuiltin("spiral",gn,"Nodes on a spiral."),e.registerBuiltin("cube",yn,"Nodes in a 3-D lattice."),e.registerBuiltin("sphere",vn,"Nodes on a sphere."),e.registerBuiltin("scatter",xn,"Nodes scattered randomly in a range."),e.registerBuiltin("ego",Sn,"Tree or rings around root node(s)."),e.registerBuiltin("tree",Cn,"Tidy tree (org chart, directory); forests supported."),e.registerBuiltin("radialTree",kn,"Tidy tree in polar form, root in the centre."),e.registerBuiltin("layered",En,"Layered (Sugiyama) layout for directed graphs: lineage, call chains, workflows."),e.registerBuiltin("columns",Fn,"One column per property value, crossings reduced inside columns."),e.registerBuiltin("rotate",bn,"Rotate current positions (transform)."),e.registerBuiltin("scale",Mn,"Scale current positions (transform)."),e.registerBuiltin("shift",wn,"Translate current positions (transform)."),e.registerBuiltin("alignBy",_n,"Align nodes by an axis (transform)."),e.registerBuiltin("plotScatter",Ln,"Scatter plot by two properties."),e.registerBuiltin("plotMultiCategoryScatter",Gn,"Scatter plot with category axes."),e}var Ki=Wi();var re=pe(require("three"),1);function Pe(){return typeof navigator<"u"&&!!navigator.gpu}async function $n(e={}){if(!Pe())throw new Error("WebGPU not available: navigator.gpu is undefined. Use the WebGL backend instead.");let t=await navigator.gpu.requestAdapter({powerPreference:e.preferHighPerformance===!1?"low-power":"high-performance"});if(!t)throw new Error("WebGPU adapter request returned null (no compatible adapter found).");let i=(e.requestedFeatures??[]).filter(o=>t.features.has(o)),r=await t.requestDevice({requiredFeatures:i});return{adapter:t,device:r,features:new Set(t.features),limits:t.limits}}function At(e){if(e<=0)return 1;let t=Math.ceil(Math.sqrt(e));return Math.pow(2,Math.ceil(Math.log2(t)))}function qe(e,t,n=10){if(e<=0)return n;let i;return t===3?i=Math.cbrt(e)*2:i=Math.sqrt(e)*.5,Math.max(n,i)}function Qi(){return{type:re.FloatType,format:re.RGBAFormat,minFilter:re.NearestFilter,magFilter:re.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1}}function Ee(e){let t=Qi();return new re.WebGLRenderTarget(e,e,t)}function Oe(e,t){let n=new re.DataTexture(e,t,t,re.RGBAFormat,re.FloatType);return n.minFilter=re.NearestFilter,n.magFilter=re.NearestFilter,n.needsUpdate=!0,n}function Zn(e){let t=[];for(let n=0;n<e;n++)for(let i=0;i<e;i++)t.push(i,n);return new Float32Array(t)}function ye(){return new re.PlaneGeometry(2,2)}function jn(e=1){let r=e;return function(){return r=(1664525*r+1013904223)%4294967296,r/4294967296}}function dt(e){return(e()-.5)*1e-6}function te(e){return()=>e}function Ve(e,t,n){let i=e.length,r=10,o=Math.PI*(3-Math.sqrt(5)),a=Math.PI*20/(9+Math.sqrt(221));for(let s=0;s<i;s++){let l=e[s];if(l.index=s,l.fx!=null&&(l.x=l.fx),l.fy!=null&&(l.y=l.fy),l.fz!=null&&(l.z=l.fz),isNaN(l.x)||t>1&&isNaN(l.y)||t>2&&isNaN(l.z)){let u=r*(t>2?Math.cbrt(.5+s):t>1?Math.sqrt(.5+s):s),c=s*o,f=s*a;t===1?l.x=u:t===2?(l.x=u*Math.cos(c),l.y=u*Math.sin(c)):(l.x=u*Math.sin(c)*Math.cos(f),l.y=u*Math.cos(c),l.z=u*Math.sin(c)*Math.sin(f))}(isNaN(l.vx)||t>1&&isNaN(l.vy)||t>2&&isNaN(l.vz))&&(l.vx=0,t>1&&(l.vy=0),t>2&&(l.vz=0))}}function Vn(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.x||0,i[a+1]=o.y||0,i[a+2]=o.z||0,i[a+3]=r}return i}function Wn(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.vx||0,i[a+1]=o.vy||0,i[a+2]=o.vz||0,i[a+3]=0}return i}function Kn(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.fx!=null||o.fy!=null||o.fz!=null?1:0,i[a+1]=0,i[a+2]=0,i[a+3]=0}return i}function Qn(e,t,n){for(let i=0;i<e.length;i++){let r=e[i],o=i*4;r.fx==null&&(r.x=t[o]),n>1&&r.fy==null&&(r.y=t[o+1]),n>2&&r.fz==null?r.z=t[o+2]:n<=2&&(r.z=0)}}var Ji=`// Position integration compute shader.
|
|
2
2
|
//
|
|
3
3
|
// One invocation per node. Reads accumulated velocity, applies velocityDecay,
|
|
4
4
|
// CLAMPS velocity magnitude to maxVel (matches WebGL FBO path's
|
|
@@ -82,7 +82,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
82
82
|
// Store the decayed-but-UNCLAMPED velocity so momentum carries to next tick.
|
|
83
83
|
velocities[i] = vec4<f32>(v, 0.0);
|
|
84
84
|
}
|
|
85
|
-
`,
|
|
85
|
+
`,Ge=16,Ne=16,On=4,er=16,tr=64;function Jn(e,t=3,n={}){let i=e,r=i.length,o=t,a=1,s=.001,l=0,u=1-Math.pow(s,1/300),c=.6,f=0,d=Math.random,p=new Map,m=new Map,g=null,y=null,w=null,M=null,h=null,v=null,b=null,x=null,C=null,E=null,A=!1,R=!1,I=!1;Ve(i,o,d),(n.device||Pe())&&L();async function L(){try{y=n.device?await n.device:await $n({preferHighPerformance:n.preferHighPerformance}),_(),z(),B(),p.forEach(S=>P(S)),A=!0,T("ready")}catch(S){console.error("[webgpuForceSimulation] device init failed:",S)}}function B(){if(!y||!w||!M||!h)return;let{device:S}=y;x?.destroy(),x=S.createBuffer({label:"integrate-params",size:er,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let D=S.createShaderModule({label:"integrate-shader",code:Ji});C=S.createComputePipeline({label:"integrate-pipeline",layout:"auto",compute:{module:D,entryPoint:"main"}}),E=S.createBindGroup({label:"integrate-bind-group",layout:C.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:w}},{binding:1,resource:{buffer:M}},{binding:2,resource:{buffer:h}},{binding:3,resource:{buffer:x}}]})}function F(){if(!y||!x)return;let S=new Float32Array([c,o,r,f]);y.device.queue.writeBuffer(x,0,S)}function _(){if(!y)return;let{device:S}=y;w?.destroy(),M?.destroy(),h?.destroy(),v?.destroy(),b?.destroy(),w=S.createBuffer({label:"positions",size:r*Ge,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),M=S.createBuffer({label:"velocities",size:r*Ne,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),h=S.createBuffer({label:"pinned",size:r*On,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),v=S.createBuffer({label:"readback",size:r*Ge,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),b=S.createBuffer({label:"readback-velocity",size:r*Ne,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST})}function z(){if(!y||!w||!M||!h)return;let{device:S}=y,D=new Float32Array(r*4),O=new Float32Array(r*4),Y=new Float32Array(r);for(let X=0;X<r;X++){let W=i[X];D[X*4+0]=W.x??0,D[X*4+1]=W.y??0,D[X*4+2]=W.z??0,D[X*4+3]=X,O[X*4+0]=W.vx??0,O[X*4+1]=W.vy??0,O[X*4+2]=W.vz??0,Y[X]=W.fx!=null||W.fy!=null||W.fz!=null?1:0}S.queue.writeBuffer(w,0,D),S.queue.writeBuffer(M,0,O),S.queue.writeBuffer(h,0,Y)}function P(S){if(!y||!w||!M||!h)return;let D={device:y.device,nodeCount:r,nDim:o,positionBuffer:w,velocityBuffer:M,pinnedBuffer:h};S.initGPU(D)}function T(S){let D=m.get(S);if(D)for(let O of D)O()}function k(S=1){if(!A||!y||!C||!E)return;let{device:D}=y;for(let O=0;O<S;O++){if(a<s){T("end");return}F();let Y=D.createCommandEncoder({label:"tick"});p.forEach(W=>W.apply(a,Y));let X=Y.beginComputePass({label:"integrate"});X.setPipeline(C),X.setBindGroup(0,E),X.dispatchWorkgroups(Math.ceil(r/tr)),X.end(),D.queue.submit([Y.finish()]),a=a+(l-a)*u,T("tick")}}async function q(){if(!(!y||!w||!v)&&!R){R=!0;try{let{device:S}=y,D=S.createCommandEncoder({label:"readback"});D.copyBufferToBuffer(w,0,v,0,r*Ge),S.queue.submit([D.finish()]);try{await v.mapAsync(GPUMapMode.READ,0,r*Ge)}catch(Y){let X=Y?.name;if(X==="AbortError"||X==="OperationError")return;throw Y}if(!v)return;let O=new Float32Array(v.getMappedRange(0,r*Ge));if(globalThis.__webgpuPathASkip===!0){(!g||g.length<O.length)&&(g=new Float32Array(O.length)),g.set(O),v.unmap();return}for(let Y=0;Y<r;Y++){let X=Y*4,W=i[Y];W.fx==null&&(W.x=O[X]),o>1&&W.fy==null&&(W.y=O[X+1]),o>2&&W.fz==null?W.z=O[X+2]:o<=2&&(W.z=0)}v.unmap()}finally{R=!1}}}async function N(){if(!y||!M||!b)return new Float32Array(0);let{device:S}=y,D=S.createCommandEncoder({label:"readback-vel"});D.copyBufferToBuffer(M,0,b,0,r*Ne),S.queue.submit([D.finish()]);try{await b.mapAsync(GPUMapMode.READ,0,r*Ne)}catch(X){if(X?.name==="AbortError")return new Float32Array(0);throw X}if(!b)return new Float32Array(0);let O=new Float32Array(b.getMappedRange(0,r*Ne)),Y=new Float32Array(O);return b.unmap(),Y}return{tick(S){return k(S??1),this},restart(){return a=1,this},stop(){return this},alpha(S){return arguments.length===0?a:(a=+S,this)},alphaMin(S){return arguments.length===0?s:(s=+S,this)},alphaDecay(S){return arguments.length===0?u:(u=+S,this)},velocityDecay(S){return arguments.length===0?c:(c=+S,this)},alphaTarget(S){return arguments.length===0?l:(l=+S,this)},maxVel(S){return arguments.length===0?f:(f=+S,this)},uploadPosition(S,D,O,Y){if(!y||!w||S<0||S>=r)return;let X=S*Ge,W=new Float32Array([D,O,Y,S]);y.device.queue.writeBuffer(w,X,W);let V=i[S];V&&(V.x=D,V.y=O,V.z=Y)},uploadVelocity(S,D,O,Y){if(!y||!M||S<0||S>=r)return;let X=S*Ne,W=new Float32Array([D,O,Y,0]);y.device.queue.writeBuffer(M,X,W);let V=i[S];V&&(V.vx=D,V.vy=O,V.vz=Y)},uploadPinned(S,D){if(!y||!h||S<0||S>=r)return;let O=S*On;y.device.queue.writeBuffer(h,O,new Float32Array([D?1:0]))},nodes(S){return arguments.length===0?i:(i=S,r=i.length,Ve(i,o,d),y&&(_(),z(),B(),p.forEach(D=>P(D))),this)},force(S,D){return arguments.length===1?p.get(S):(D==null?p.delete(S):(D.initialize(i,d,o),p.set(S,D),y&&P(D)),this)},numDimensions(S){return arguments.length===0?o:(o=+S,F(),p.forEach(D=>D.initialize(i,d,o)),this)},on(S,D){let O=m.get(S);return O||(O=[],m.set(S,O)),O.push(D),this},dispose(){w?.destroy(),M?.destroy(),h?.destroy(),v?.destroy(),b?.destroy(),x?.destroy(),w=M=h=v=null,b=null,x=null,C=null,E=null,p.forEach(S=>S.dispose?.()),p.clear(),A=!1},isReady(){return A},readPositions(){return q()},readVelocities(){return N()},getDevice(){return y?.device??null},getPositionBuffer(){return w}}}var nr=`// forceCenter \u2014 pass 1 of 2: parallel reduce centroid \u2192 shift vector.
|
|
86
86
|
//
|
|
87
87
|
// Computes mean(positions) across all nodes inside a single workgroup using
|
|
88
88
|
// shared memory, then writes (mean - target) * strength to shift[0].
|
|
@@ -157,7 +157,7 @@ fn main(@builtin(local_invocation_id) lid: vec3<u32>) {
|
|
|
157
157
|
shift[0] = vec4<f32>(s, 0.0);
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
|
-
`,
|
|
160
|
+
`,ir=`// forceCenter \u2014 pass 2 of 2: subtract shift from every node's position.
|
|
161
161
|
//
|
|
162
162
|
// Mirrors d3-force-3d center.js: \`node.x -= shift\`. Pinned nodes are skipped.
|
|
163
163
|
// One invocation per node.
|
|
@@ -192,7 +192,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
192
192
|
if (params.nDim < 2.0) { p.y = 0.0; }
|
|
193
193
|
positions[i] = vec4<f32>(p, positions[i].w);
|
|
194
194
|
}
|
|
195
|
-
`,
|
|
195
|
+
`,rr=16,ar=32,or=16,sr=64;function ei(e=0,t=0,n=0){let i=e,r=t,o=n,a=1,s=3,l=0,u=null,c=null,f=null,d=null,p=null,m=null,g=null,y=null;function w(C,E,A){s=A}function M(C){u=C.device,l=C.nodeCount,s=C.nDim,c?.destroy(),c=u.createBuffer({label:"center-shift",size:rr,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),f?.destroy(),f=u.createBuffer({label:"center-reduce-params",size:ar,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),d?.destroy(),d=u.createBuffer({label:"center-apply-params",size:or,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let E=u.createShaderModule({label:"center-reduce-shader",code:nr});p=u.createComputePipeline({label:"center-reduce-pipeline",layout:"auto",compute:{module:E,entryPoint:"main"}});let A=u.createShaderModule({label:"center-apply-shader",code:ir});m=u.createComputePipeline({label:"center-apply-pipeline",layout:"auto",compute:{module:A,entryPoint:"main"}}),g=u.createBindGroup({label:"center-reduce-bind-group",layout:p.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:C.positionBuffer}},{binding:1,resource:{buffer:c}},{binding:2,resource:{buffer:f}}]}),y=u.createBindGroup({label:"center-apply-bind-group",layout:m.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:C.positionBuffer}},{binding:1,resource:{buffer:C.pinnedBuffer}},{binding:2,resource:{buffer:c}},{binding:3,resource:{buffer:d}}]})}function h(){if(!u||!f||!d)return;let C=new Float32Array([l,s,a,0,i,r,o,0]);u.queue.writeBuffer(f,0,C);let E=new Float32Array([l,s,0,0]);u.queue.writeBuffer(d,0,E)}function v(C,E){if(!p||!m||!g||!y||l===0)return;h();let A=E.beginComputePass({label:"center-reduce"});A.setPipeline(p),A.setBindGroup(0,g),A.dispatchWorkgroups(1),A.end();let R=E.beginComputePass({label:"center-apply"});R.setPipeline(m),R.setBindGroup(0,y),R.dispatchWorkgroups(Math.ceil(l/sr)),R.end()}function b(){c?.destroy(),f?.destroy(),d?.destroy(),c=f=d=null,p=m=null,g=y=null,u=null}let x={initialize:w,initGPU:M,apply:v,dispose:b,x(C){return arguments.length===0?i:(i=+C,x)},y(C){return arguments.length===0?r:(r=+C,x)},z(C){return arguments.length===0?o:(o=+C,x)},strength(C){return arguments.length===0?a:(a=+C,x)}};return x}var lr=`// Per-axis attractive force (forceX / forceY / forceZ).
|
|
196
196
|
//
|
|
197
197
|
// One invocation per node. Adds \`(target - position[axis]) * strength * alpha\`
|
|
198
198
|
// to that node's velocity along the configured axis only \u2014 other axes untouched.
|
|
@@ -241,7 +241,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
241
241
|
|
|
242
242
|
velocities[i] = vec4<f32>(vel, velocities[i].w);
|
|
243
243
|
}
|
|
244
|
-
`,
|
|
244
|
+
`,ur=32,cr=64;function Rt(e,t){let n=t,i=.1,r=0,o=null,a=null,s=null,l=null;function u(){}function c(g){o=g.device,r=g.nodeCount,a?.destroy(),a=o.createBuffer({label:`position-force-${e}-params`,size:ur,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let y=o.createShaderModule({label:`position-force-${e}-shader`,code:lr});s=o.createComputePipeline({label:`position-force-${e}-pipeline`,layout:"auto",compute:{module:y,entryPoint:"main"}}),l=o.createBindGroup({label:`position-force-${e}-bind-group`,layout:s.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:g.positionBuffer}},{binding:1,resource:{buffer:g.velocityBuffer}},{binding:2,resource:{buffer:a}}]})}function f(g){if(!o||!a)return;let y=new Float32Array([e,n,i,g,r,0,0,0]);o.queue.writeBuffer(a,0,y)}function d(g,y){if(!s||!l||r===0)return;f(g);let w=y.beginComputePass({label:`position-force-${e}`});w.setPipeline(s),w.setBindGroup(0,l),w.dispatchWorkgroups(Math.ceil(r/cr)),w.end()}function p(){a?.destroy(),a=null,s=null,l=null,o=null}let m={initialize:u,initGPU:c,apply:d,dispose:p,strength(g){return arguments.length===0?i:(i=+g,m)},target(g){return arguments.length===0?n:(n=+g,m)}};return m}function ti(e=0){return Rt(0,e)}function ni(e=0){return Rt(1,e)}function ii(e=0){return Rt(2,e)}var dr=`// forceLink \u2014 per-edge spring constraint.
|
|
245
245
|
//
|
|
246
246
|
// One invocation per edge. For each edge (s, t), computes a delta toward the
|
|
247
247
|
// configured \`linkDistance\` and accumulates contributions into an integer
|
|
@@ -323,7 +323,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
323
323
|
atomicSub(&velAccum[tIdx * 3u + 1u], i32(tgtShare.y * FIXED_POINT_SCALE));
|
|
324
324
|
atomicSub(&velAccum[tIdx * 3u + 2u], i32(tgtShare.z * FIXED_POINT_SCALE));
|
|
325
325
|
}
|
|
326
|
-
|
|
326
|
+
`,fr=`// forceLink pass 2: drain the i32 atomic accumulator into f32 velocities.
|
|
327
327
|
//
|
|
328
328
|
// One invocation per node. Reads the 3 i32 slots populated by link-force.wgsl,
|
|
329
329
|
// converts back to f32 (divides by FIXED_POINT_SCALE), adds to velocity, then
|
|
@@ -360,7 +360,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
360
360
|
let delta = vec3<f32>(f32(ax), f32(ay), f32(az)) / FIXED_POINT_SCALE;
|
|
361
361
|
velocities[i] = vec4<f32>(velocities[i].xyz + delta, velocities[i].w);
|
|
362
362
|
}
|
|
363
|
-
`,
|
|
363
|
+
`,pr=12,hr=16,mr=16,Hn=64;function gr(e){return()=>e}function ri(e=[]){let t=e,n=new Int32Array(0),i=30,r=[],o=0,a=null,s=null,l=null,u=null,c=null,f=null,d=null,p=null,m=null,g=null,y=0,w=new Float32Array(0),M=null,h=null;function v(P){let T=P.source,k=P.target,q=Math.min(n[T]??1,n[k]??1);return q>0?1/q:1}let b=v;function x(P,T,k){r=P}function C(){let P=new Map;for(let N=0;N<r.length;N++){let G=r[N];G.id!=null&&P.set(G.id,N),G.index!=null&&P.set(G.index,N)}let T=new Int32Array(r.length),k=[];for(let N=0;N<t.length;N++){let G=t[N],S=E(G.source,P),D=E(G.target,P);S<0||D<0||(T[S]++,T[D]++,k.push({source:S,target:D,index:N}))}n=T;let q=new Float32Array(k.length*4);w=new Float32Array(k.length);for(let N=0;N<k.length;N++){let G=k[N].source,S=k[N].target,D=T[G]+T[S],O=D>0?T[G]/D:.5;q[N*4+0]=G,q[N*4+1]=S,q[N*4+2]=O,q[N*4+3]=i,w[N]=+b(k[N],N,k)}return y=k.length,q}function E(P,T){if(typeof P=="object"&&P!==null){let k=P;return k.index!=null?k.index:k.id!=null?T.get(k.id)??-1:-1}return T.get(P)??-1}function A(){if(!a)return;let P=C();if(s?.destroy(),l?.destroy(),P.length===0){s=null,l=null;return}s=a.createBuffer({label:"link-edges",size:P.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),a.queue.writeBuffer(s,0,P.buffer,P.byteOffset,P.byteLength),l=a.createBuffer({label:"link-strengths",size:Math.max(w.byteLength,4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),a.queue.writeBuffer(l,0,w.buffer,w.byteOffset,w.byteLength),h&&M&&I(h,M)}function R(P){a=P.device,o=P.nodeCount,u?.destroy(),u=a.createBuffer({label:"link-vel-accum",size:o*pr,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});let T=new Int32Array(o*3);a.queue.writeBuffer(u,0,T.buffer,0,T.byteLength),c?.destroy(),c=a.createBuffer({label:"link-params",size:hr,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),f?.destroy(),f=a.createBuffer({label:"link-drain-params",size:mr,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let k=a.createShaderModule({label:"link-force-shader",code:dr});d=a.createComputePipeline({label:"link-force-pipeline",layout:"auto",compute:{module:k,entryPoint:"main"}});let q=a.createShaderModule({label:"link-drain-shader",code:fr});p=a.createComputePipeline({label:"link-drain-pipeline",layout:"auto",compute:{module:q,entryPoint:"main"}}),A(),I(P.positionBuffer,P.velocityBuffer)}function I(P,T){!a||!d||!p||!u||!c||!f||(M=T,h=P,s&&l?m=a.createBindGroup({label:"link-force-bind-group",layout:d.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:P}},{binding:1,resource:{buffer:u}},{binding:2,resource:{buffer:s}},{binding:3,resource:{buffer:c}},{binding:4,resource:{buffer:l}},{binding:5,resource:{buffer:T}}]}):m=null,g=a.createBindGroup({label:"link-drain-bind-group",layout:p.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:T}},{binding:1,resource:{buffer:u}},{binding:2,resource:{buffer:f}}]}))}function L(){A()}function B(P){if(!a||!c||!f)return;let T=new Float32Array([y,0,P,0]);a.queue.writeBuffer(c,0,T);let k=new Float32Array([o,0,0,0]);a.queue.writeBuffer(f,0,k)}function F(P,T){if(!d||!p||!g||o===0)return;if(B(P),m&&y>0){let q=T.beginComputePass({label:"link-force"});q.setPipeline(d),q.setBindGroup(0,m),q.dispatchWorkgroups(Math.ceil(y/Hn)),q.end()}let k=T.beginComputePass({label:"link-drain"});k.setPipeline(p),k.setBindGroup(0,g),k.dispatchWorkgroups(Math.ceil(o/Hn)),k.end()}function _(){s?.destroy(),l?.destroy(),u?.destroy(),c?.destroy(),f?.destroy(),s=l=u=c=f=null,d=p=null,m=g=null,M=null,h=null,a=null}let z={initialize:x,initGPU:R,apply:F,dispose:_,links(P){return arguments.length===0?t:(t=P,a&&A(),z)},strength(P){return arguments.length===0?b:(b=typeof P=="function"?P:gr(+P),a&&A(),z)},distance(P){return arguments.length===0?i:(i=+P,a&&A(),z)},rebuildEdgeBuffer:L};return z}var ai=64,Te=32,yr=.9;function vr(e){return e<=1?1:1<<Math.ceil(Math.log2(e))}function xr(e,t,n){let i=t,r=vr(i),o=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,a=e.createBuffer({label:"lbvh-morton",size:r*4,usage:o}),s=e.createBuffer({label:"lbvh-sortedIndices",size:r*4,usage:o}),l=e.createBuffer({label:"lbvh-internal",size:Math.max(1,i-1)*16,usage:o}),u=e.createBuffer({label:"lbvh-parent",size:Math.max(1,i-1)*4,usage:o}),c=e.createBuffer({label:"lbvh-aabb",size:Math.max(1,2*i-1)*32,usage:o}),f=e.createBuffer({label:"lbvh-com",size:Math.max(1,2*i-1)*16,usage:o}),d=e.createBuffer({label:"lbvh-depth",size:Math.max(1,i-1)*4,usage:o}),p=e.createBuffer({label:"lbvh-bounds",size:32,usage:o}),m=e.createBuffer({label:"lbvh-queueA",size:Math.max(1,i-1)*4,usage:o}),g=e.createBuffer({label:"lbvh-queueB",size:Math.max(1,i-1)*4,usage:o}),y=e.createBuffer({label:"lbvh-frontier",size:(n+1)*4,usage:o}),w=e.createBuffer({label:"lbvh-root",size:4,usage:o});return{paddedN:r,morton:a,sortedIndices:s,internal:l,parent:u,aabb:c,com:f,depth:d,bounds:p,depthQueueA:m,depthQueueB:g,frontierCounts:y,root:w,dispose(){for(let M of[a,s,l,u,c,f,d,p,m,g,y,w])M.destroy()}}}var Ut=`// P1: scene AABB via atomicMin/atomicMax on i32 bit-reinterpretation of f32 positions.
|
|
364
364
|
// Uses ordered-i32 trick: for positive floats, integer bit pattern preserves order;
|
|
365
365
|
// for negative, flipping all bits restores order. Inverse on read recovers f32.
|
|
366
366
|
|
|
@@ -387,7 +387,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
387
387
|
atomicMin(&bounds[2], yi); atomicMax(&bounds[3], yi);
|
|
388
388
|
atomicMin(&bounds[4], zi); atomicMax(&bounds[5], zi);
|
|
389
389
|
}
|
|
390
|
-
`,
|
|
390
|
+
`,br=`// P2: per-node Morton code from normalized position. Mirrors mortonReference.ts exactly.
|
|
391
391
|
|
|
392
392
|
struct MortonParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
|
|
393
393
|
|
|
@@ -428,7 +428,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
428
428
|
mortons[i] = mortonExpand10(xi) | (mortonExpand10(yi) << 1u) | (mortonExpand10(zi) << 2u);
|
|
429
429
|
sortedIndices[i] = i;
|
|
430
430
|
}
|
|
431
|
-
`,
|
|
431
|
+
`,Mr=`// P4: Karras-2012 binary radix tree build. One thread per internal node (N-1 threads).
|
|
432
432
|
// Each internal node i covers a range of sorted Morton codes; the split is the largest
|
|
433
433
|
// prefix-difference inside the range.
|
|
434
434
|
//
|
|
@@ -527,7 +527,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
527
527
|
if (!leftIsLeaf) { parentBuf[leftChild] = i; }
|
|
528
528
|
if (!rightIsLeaf) { parentBuf[rightChild] = i; }
|
|
529
529
|
}
|
|
530
|
-
`,
|
|
530
|
+
`,wr=`// P4b: find the root internal node. The root is the unique internal node with
|
|
531
531
|
// parentBuf[i] == -1 (parentBuf is pre-initialized to -1 by orchestrator; P4 overwrote
|
|
532
532
|
// it for every child of every internal node, so only the root remains at -1).
|
|
533
533
|
|
|
@@ -548,7 +548,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
548
548
|
rootOut[0] = u32(i);
|
|
549
549
|
}
|
|
550
550
|
}
|
|
551
|
-
`,
|
|
551
|
+
`,_r=`// P5: BFS ping-pong. One dispatch per BFS level (LBVH_MAX_DEPTH total = 32, empty levels are no-ops).
|
|
552
552
|
// FrontierCount comes from a GPU-side counter buffer (no CPU readback). currentDepth
|
|
553
553
|
// is the only per-dispatch param and uses a DEDICATED per-dispatch uniform buffer
|
|
554
554
|
// (one of LBVH_MAX_DEPTH=32, allocated once in orchestrator init).
|
|
@@ -593,7 +593,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
593
593
|
queueOut[slot] = u32(rightChild);
|
|
594
594
|
}
|
|
595
595
|
}
|
|
596
|
-
`,
|
|
596
|
+
`,Sr=`// P6: COM and AABB reduce.
|
|
597
597
|
// Two entry points, selected by pipeline at dispatch time:
|
|
598
598
|
// leafInit: initialize comBuffer[N-1..2N-2] from leaf positions.
|
|
599
599
|
// levelReduce: for each internal node at depthBuffer[i] == currentLevel, combine
|
|
@@ -650,7 +650,7 @@ fn levelReduce(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
650
650
|
aabbBuffer[2u * i] = vec4<f32>(min(aabbMinL, aabbMinR), 0.0);
|
|
651
651
|
aabbBuffer[2u * i + 1u] = vec4<f32>(max(aabbMaxL, aabbMaxR), 0.0);
|
|
652
652
|
}
|
|
653
|
-
`,
|
|
653
|
+
`,Tr=`// P7: per-query-node DFS traversal with Barnes-Hut criterion. One thread per node.
|
|
654
654
|
// Writes accumulated velocity directly to velocities[i].xyz (no atomics needed \u2014
|
|
655
655
|
// each thread owns its own output slot). Self-interaction guard skips the query
|
|
656
656
|
// node's own entry in leaf cells.
|
|
@@ -760,7 +760,7 @@ fn main(
|
|
|
760
760
|
|
|
761
761
|
velocities[queryIdx] = vec4<f32>(velocities[queryIdx].xyz + accum, velocities[queryIdx].w);
|
|
762
762
|
}
|
|
763
|
-
`,
|
|
763
|
+
`,Pr=`// P3: one bitonic compare-swap step. Dispatched once per (k, j) in bitonicSortSteps().
|
|
764
764
|
|
|
765
765
|
struct SortParams { n: u32, k: u32, j: u32, _pad: u32 };
|
|
766
766
|
|
|
@@ -789,7 +789,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
789
789
|
values[partner] = vI;
|
|
790
790
|
}
|
|
791
791
|
}
|
|
792
|
-
`;function
|
|
792
|
+
`;function Br(e){let t=[];for(let n=2;n<=e;n*=2)for(let i=n/2;i>0;i=i>>1)t.push({k:n,j:i});return t}var zr=16,Cr=class{constructor(e){this.device=e,this.paramsBuffers=[];let t=e.createShaderModule({label:"lbvh-sort",code:Pr});this.pipeline=e.createComputePipeline({label:"lbvh-sort-pipeline",layout:"auto",compute:{module:t,entryPoint:"main"}})}ensureParamsBuffer(e){for(;this.paramsBuffers.length<=e;)this.paramsBuffers.push(this.device.createBuffer({label:`lbvh-sort-params-${this.paramsBuffers.length}`,size:zr,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));return this.paramsBuffers[e]}sort(e,t,n,i){let r=Br(i);for(let o=0;o<r.length;o++){let{k:a,j:s}=r[o],l=this.ensureParamsBuffer(o);this.device.queue.writeBuffer(l,0,new Uint32Array([i,a,s,0]));let u=this.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:n}},{binding:2,resource:{buffer:l}}]}),c=e.beginComputePass({label:`bitonic k=${a} j=${s}`});c.setPipeline(this.pipeline),c.setBindGroup(0,u),c.dispatchWorkgroups(Math.ceil(i/ai)),c.end()}}dispose(){for(let e of this.paramsBuffers)e.destroy();this.paramsBuffers=[]}},kr=class{constructor(e,t){this.ctx=e,this.buffers=t,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,t=(o,a=16)=>e.createBuffer({label:o,size:a,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.boundsParamsBuf=t("lbvh-bounds-params"),this.mortonParamsBuf=t("lbvh-morton-params"),this.buildParamsBuf=t("lbvh-build-params"),this.findRootParamsBuf=t("lbvh-find-root-params"),this.traverseParamsBuf=t("lbvh-traverse-params",32);for(let o=0;o<Te;o++){let a=t(`lbvh-depths-params-${o}`);e.queue.writeBuffer(a,0,new Uint32Array([this.nodeCount,o,0,0])),this.depthsParamsBufs.push(a)}for(let o=0;o<=Te;o++){let a=t(`lbvh-reduce-params-${o}`);e.queue.writeBuffer(a,0,new Uint32Array([this.nodeCount,o===0?0:o-1,0,0])),this.reduceParamsBufs.push(a)}let n=(o,a)=>e.createShaderModule({label:o,code:a}),i=(o,a,s)=>e.createComputePipeline({label:o,layout:"auto",compute:{module:a,entryPoint:s}});this.boundsPipeline=i("lbvh-bounds",n("lbvh-bounds",Ut),"main"),this.mortonPipeline=i("lbvh-morton",n("lbvh-morton",br),"main"),this.buildPipeline=i("lbvh-build",n("lbvh-build",Mr),"main"),this.findRootPipeline=i("lbvh-find-root",n("lbvh-find-root",wr),"main"),this.depthsPipeline=i("lbvh-depths",n("lbvh-depths",_r),"main");let r=n("lbvh-reduce",Sr);this.reduceLeafInitPipeline=i("lbvh-reduce-leafInit",r,"leafInit"),this.reduceLevelPipeline=i("lbvh-reduce-level",r,"levelReduce"),this.traversePipeline=i("lbvh-traverse",n("lbvh-traverse",Tr),"main"),this.sortPass=new Cr(e),this.bindAll()}bindAll(){let e=this.ctx.device,t=this.buffers,n=this.ctx;this.boundsBG=e.createBindGroup({layout:this.boundsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.positions}},{binding:1,resource:{buffer:t.bounds}},{binding:2,resource:{buffer:this.boundsParamsBuf}}]}),this.mortonBG=e.createBindGroup({layout:this.mortonPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.positions}},{binding:1,resource:{buffer:t.bounds}},{binding:2,resource:{buffer:t.morton}},{binding:3,resource:{buffer:t.sortedIndices}},{binding:4,resource:{buffer:this.mortonParamsBuf}}]}),this.buildBG=e.createBindGroup({layout:this.buildPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.morton}},{binding:1,resource:{buffer:t.internal}},{binding:2,resource:{buffer:t.parent}},{binding:3,resource:{buffer:t.aabb}},{binding:4,resource:{buffer:t.sortedIndices}},{binding:5,resource:{buffer:n.positions}},{binding:6,resource:{buffer:this.buildParamsBuf}}]}),this.findRootBG=e.createBindGroup({layout:this.findRootPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.parent}},{binding:1,resource:{buffer:t.root}},{binding:2,resource:{buffer:this.findRootParamsBuf}}]});for(let i=0;i<Te;i++)this.depthsBG_AtoB.push(e.createBindGroup({layout:this.depthsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.internal}},{binding:1,resource:{buffer:t.depthQueueA}},{binding:2,resource:{buffer:t.depthQueueB}},{binding:3,resource:{buffer:t.frontierCounts}},{binding:4,resource:{buffer:t.depth}},{binding:5,resource:{buffer:this.depthsParamsBufs[i]}}]})),this.depthsBG_BtoA.push(e.createBindGroup({layout:this.depthsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.internal}},{binding:1,resource:{buffer:t.depthQueueB}},{binding:2,resource:{buffer:t.depthQueueA}},{binding:3,resource:{buffer:t.frontierCounts}},{binding:4,resource:{buffer:t.depth}},{binding:5,resource:{buffer:this.depthsParamsBufs[i]}}]}));this.reduceLeafInitBG=e.createBindGroup({layout:this.reduceLeafInitPipeline.getBindGroupLayout(0),entries:[{binding:1,resource:{buffer:t.com}},{binding:4,resource:{buffer:t.sortedIndices}},{binding:5,resource:{buffer:n.positions}},{binding:6,resource:{buffer:this.reduceParamsBufs[0]}}]});for(let i=0;i<Te;i++)this.reduceLevelBGs.push(e.createBindGroup({layout:this.reduceLevelPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.internal}},{binding:1,resource:{buffer:t.com}},{binding:2,resource:{buffer:t.aabb}},{binding:3,resource:{buffer:t.depth}},{binding:6,resource:{buffer:this.reduceParamsBufs[i+1]}}]}));this.traverseBG=e.createBindGroup({layout:this.traversePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.positions}},{binding:1,resource:{buffer:n.velocities}},{binding:2,resource:{buffer:t.internal}},{binding:3,resource:{buffer:t.com}},{binding:4,resource:{buffer:t.aabb}},{binding:5,resource:{buffer:t.sortedIndices}},{binding:6,resource:{buffer:t.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,t){let n=this.ctx.device,i=this.nodeCount;if(i<2)return;let r=ai,o=Math.ceil(i/r),a=Math.ceil(Math.max(1,i-1)/r),s=this.buffers.paddedN,l=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);if(n.queue.writeBuffer(this.buffers.bounds,0,l),s>i){let p=new Uint32Array(s-i).fill(4294967295),m=new Uint32Array(s-i).fill(4294967295);n.queue.writeBuffer(this.buffers.morton,i*4,p),n.queue.writeBuffer(this.buffers.sortedIndices,i*4,m)}let u=new Int32Array(Math.max(1,i-1)).fill(-1);n.queue.writeBuffer(this.buffers.parent,0,u);let c=new Uint32Array(Te+1);c[0]=1,n.queue.writeBuffer(this.buffers.frontierCounts,0,c),n.queue.writeBuffer(this.buffers.root,0,new Uint32Array([0]));let f=Number.isFinite(this.distanceMax)?this.distanceMax*this.distanceMax:34e37,d=new ArrayBuffer(32);new Uint32Array(d,0,1)[0]=i,new Float32Array(d,4,5).set([this.strength,e,this.theta*this.theta,this.distanceMin*this.distanceMin,f]),n.queue.writeBuffer(this.traverseParamsBuf,0,d),this.runSimple(t,this.boundsPipeline,this.boundsBG,o,"p1-bounds"),this.runSimple(t,this.mortonPipeline,this.mortonBG,o,"p2-morton"),this.sortPass.sort(t,this.buffers.morton,this.buffers.sortedIndices,s),this.runSimple(t,this.buildPipeline,this.buildBG,Math.max(a,o),"p4-build"),this.runSimple(t,this.findRootPipeline,this.findRootBG,a,"p4b-find-root"),t.copyBufferToBuffer(this.buffers.root,0,this.buffers.depthQueueA,0,4);for(let p=0;p<Te;p++){let g=p%2===0?this.depthsBG_AtoB[p]:this.depthsBG_BtoA[p],y=t.beginComputePass({label:`p5-depths-${p}`});y.setPipeline(this.depthsPipeline),y.setBindGroup(0,g),y.dispatchWorkgroups(a),y.end()}this.runSimple(t,this.reduceLeafInitPipeline,this.reduceLeafInitBG,o,"p6-leafInit");for(let p=Te-1;p>=0;p--)this.runSimple(t,this.reduceLevelPipeline,this.reduceLevelBGs[p],a,`p6-level-${p}`);this.runSimple(t,this.traversePipeline,this.traverseBG,o,"p7-traverse")}runSimple(e,t,n,i,r){let o=e.beginComputePass({label:r});o.setPipeline(t),o.setBindGroup(0,n),o.dispatchWorkgroups(i),o.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 oi(){let e=-30,t=yr,n=1,i=1/0,r=null,o=null,a={initialize(s,l,u){},initGPU(s){(o||r)&&(o?.dispose(),r?.dispose(),o=null,r=null),r=xr(s.device,s.nodeCount,Te);let l={device:s.device,nodeCount:s.nodeCount,positions:s.positionBuffer,velocities:s.velocityBuffer};o=new kr(l,r),o.setStrength(e),o.setTheta(t),o.setDistanceMin(n),o.setDistanceMax(i)},apply(s,l){o?.apply(s,l)},dispose(){o?.dispose(),r?.dispose(),o=null,r=null},strength(s){return arguments.length===0?e:(e=+s,o?.setStrength(e),a)},theta(s){return arguments.length===0?t:(t=+s,o?.setTheta(t),a)},distanceMin(s){return arguments.length===0?n:(n=+s,o?.setDistanceMin(n),a)},distanceMax(s){return arguments.length===0?i:(i=+s,o?.setDistanceMax(i),a)}};return a}var si=`// Clear quadtree cell buffer to zero. One thread per cell slot (4 i32s/cell).
|
|
793
793
|
//
|
|
794
794
|
// Layout:
|
|
795
795
|
// group(0)
|
|
@@ -816,7 +816,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
816
816
|
if (i >= params.cellSlotCount) { return; }
|
|
817
817
|
atomicStore(&cells[i], 0);
|
|
818
818
|
}
|
|
819
|
-
`,
|
|
819
|
+
`,Er=`// quad-bin: per-node atomic write of (x, y, mass) into the LEAF cell at MAX level
|
|
820
820
|
// of a fixed-depth 2D quadtree. Reads bounds directly from boundsBuffer (ordered-int
|
|
821
821
|
// encoding produced by lbvh-bounds.wgsl).
|
|
822
822
|
//
|
|
@@ -883,7 +883,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
883
883
|
atomicAdd(&cells[baseSlot + 1u], yFixed);
|
|
884
884
|
atomicAdd(&cells[baseSlot + 3u], 1i);
|
|
885
885
|
}
|
|
886
|
-
`,
|
|
886
|
+
`,Fr=`// quad-accumulate: bottom-up COM aggregation.
|
|
887
887
|
//
|
|
888
888
|
// Dispatched once per level k (from MAX_LEVEL-1 down to 0). For each cell at
|
|
889
889
|
// level k (4^k cells), read its 4 children at level k+1 (Morton-contiguous:
|
|
@@ -925,7 +925,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
925
925
|
atomicStore(&cells[parentBase + 1u], sy);
|
|
926
926
|
atomicStore(&cells[parentBase + 3u], sm);
|
|
927
927
|
}
|
|
928
|
-
`,
|
|
928
|
+
`,Ir=`// quad-traverse: per-query-node Barnes-Hut DFS over a fixed-depth 2D quadtree.
|
|
929
929
|
// Matches d3-force-3d's apply() (manyBody.js).
|
|
930
930
|
//
|
|
931
931
|
// Reads bounds directly from boundsBuffer to compute cellWidth at each level.
|
|
@@ -1104,7 +1104,7 @@ fn main(
|
|
|
1104
1104
|
velocities[queryIdx].w,
|
|
1105
1105
|
);
|
|
1106
1106
|
}
|
|
1107
|
-
`,
|
|
1107
|
+
`,Dr=8,kt=64,Xn=64,Et=4;function Ar(e){return Math.floor((Math.pow(4,e+1)-1)/3)}function ut(e){return Math.floor((Math.pow(4,e)-1)/3)}var Rr=class{constructor(e,t=Dr){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=t,this.totalCells=Ar(t);let n=this.device,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST;this.cellsBuffer=n.createBuffer({label:"quad-cells",size:this.totalCells*Et*4,usage:i}),this.boundsBuffer=n.createBuffer({label:"quad-bounds",size:32,usage:i}),this.levelOffsetsBuffer=n.createBuffer({label:"quad-level-offsets",size:(t+1)*4,usage:i});let o=new Uint32Array(t+1);for(let f=0;f<=t;f++)o[f]=ut(f);n.queue.writeBuffer(this.levelOffsetsBuffer,0,o),this.boundsParamsBuf=n.createBuffer({label:"quad-bounds-params",size:16,usage:r}),this.clearParamsBuf=n.createBuffer({label:"quad-clear-params",size:16,usage:r}),this.binParamsBuf=n.createBuffer({label:"quad-bin-params",size:16,usage:r}),this.traverseParamsBuf=n.createBuffer({label:"quad-traverse-params",size:48,usage:r});for(let f=0;f<t;f++){let d=n.createBuffer({label:`quad-accum-params-L${f}`,size:16,usage:r}),p=new Uint32Array([ut(f),ut(f+1),Math.pow(4,f),0]);n.queue.writeBuffer(d,0,p),this.accumParamsBufs.push(d)}let a=this.totalCells*Et,l=Math.ceil(a/kt)*kt;n.queue.writeBuffer(this.clearParamsBuf,0,new Uint32Array([a,l,0,0]));let u=(f,d)=>n.createShaderModule({label:f,code:d}),c=(f,d,p="main")=>n.createComputePipeline({label:f,layout:"auto",compute:{module:d,entryPoint:p}});this.boundsPipeline=c("quad-bounds-pipe",u("quad-bounds",Ut)),this.clearPipeline=c("quad-clear-pipe",u("quad-clear",si)),this.binPipeline=c("quad-bin-pipe",u("quad-bin",Er)),this.accumPipeline=c("quad-accum-pipe",u("quad-accum",Fr)),this.traversePipeline=c("quad-traverse-pipe",u("quad-traverse",Ir)),this.bindAll(e)}bindAll(e){let t=this.device;this.boundsBG=t.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=t.createBindGroup({layout:this.clearPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.clearParamsBuf}}]}),this.binBG=t.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 i=0;i<this.maxLevel;i++)this.accumBGs.push(t.createBindGroup({layout:this.accumPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.accumParamsBufs[i]}}]}));this.traverseBG=t.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 n=new ArrayBuffer(16);new Uint32Array(n,0,3).set([this.nodeCount,this.maxLevel,ut(this.maxLevel)]),new Float32Array(n,12,1)[0]=Xn,t.queue.writeBuffer(this.binParamsBuf,0,n),t.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]))}setConfig(e){Object.assign(this.config,e)}apply(e,t){let n=this.device,i=this.nodeCount,r=kt,o=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);n.queue.writeBuffer(this.boundsBuffer,0,o),this.run(t,this.boundsPipeline,this.boundsBG,Math.ceil(i/r),"quad-p1-bounds"),this.run(t,this.clearPipeline,this.clearBG,Math.ceil(this.totalCells*Et/r),"quad-p2-clear"),this.run(t,this.binPipeline,this.binBG,Math.ceil(i/r),"quad-p3-bin");for(let u=this.maxLevel-1;u>=0;u--)this.run(t,this.accumPipeline,this.accumBGs[u],Math.ceil(Math.pow(4,u)/r),`quad-p4-accum-L${u}`);let a=new ArrayBuffer(48),s=new Uint32Array(a),l=new Float32Array(a);s[0]=i,s[1]=this.maxLevel,l[4]=this.config.strength,l[5]=e,l[6]=this.config.theta*this.config.theta,l[7]=this.config.distanceMin*this.config.distanceMin,l[8]=this.config.distanceMax===1/0?1e30:this.config.distanceMax*this.config.distanceMax,l[9]=Xn,n.queue.writeBuffer(this.traverseParamsBuf,0,a),this.run(t,this.traversePipeline,this.traverseBG,Math.ceil(i/r),"quad-p5-traverse")}run(e,t,n,i,r){let o=e.beginComputePass({label:r});o.setPipeline(t),o.setBindGroup(0,n),o.dispatchWorkgroups(i),o.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 Ur(){let e=-30,t=1,n=1/0,i=.9,r=null,o={initialize(a,s,l){},initGPU(a){r?.dispose(),r=new Rr(a),r.setConfig({strength:e,theta:i,distanceMin:t,distanceMax:n})},apply(a,s){r?.apply(a,s)},dispose(){r?.dispose(),r=null},strength(a){return arguments.length===0?e:(e=+a,r?.setConfig({strength:e}),o)},distanceMin(a){return arguments.length===0?t:(t=+a,r?.setConfig({distanceMin:t}),o)},distanceMax(a){return arguments.length===0?n:(n=+a,r?.setConfig({distanceMax:n}),o)},theta(a){return arguments.length===0?i:(i=+a,r?.setConfig({theta:i}),o)}};return o}var Lr=`// oct-bin: 3D version of quad-bin. Per-node atomic write of (x, y, z, mass)
|
|
1108
1108
|
// into the LEAF cell at MAX level of a fixed-depth 3D octree.
|
|
1109
1109
|
// Cell address: leafOffset + morton3D(cellX, cellY, cellZ).
|
|
1110
1110
|
|
|
@@ -1174,7 +1174,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
1174
1174
|
atomicAdd(&cells[baseSlot + 2u], zFixed);
|
|
1175
1175
|
atomicAdd(&cells[baseSlot + 3u], 1i);
|
|
1176
1176
|
}
|
|
1177
|
-
`,
|
|
1177
|
+
`,Gr=`// oct-accumulate: bottom-up COM aggregation for 3D octree.
|
|
1178
1178
|
//
|
|
1179
1179
|
// Mirrors d3-force-3d's manyBody accumulate:
|
|
1180
1180
|
// strength += child.value;
|
|
@@ -1222,7 +1222,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
1222
1222
|
atomicStore(&cells[parentBase + 2u], sz);
|
|
1223
1223
|
atomicStore(&cells[parentBase + 3u], sm);
|
|
1224
1224
|
}
|
|
1225
|
-
`,
|
|
1225
|
+
`,Nr=`// oct-traverse: per-query-node Barnes-Hut DFS over fixed-depth 3D octree.
|
|
1226
1226
|
// Mirrors quad-traverse.wgsl with 8 children per cell + z axis.
|
|
1227
1227
|
//
|
|
1228
1228
|
// BH criterion uses MAX axis extent of bounds (cell width = boundsMax / 2^level).
|
|
@@ -1423,7 +1423,7 @@ fn main(
|
|
|
1423
1423
|
velocities[queryIdx].w,
|
|
1424
1424
|
);
|
|
1425
1425
|
}
|
|
1426
|
-
`,Mr=7,Pt=64,kn=64,Oa=Math.sqrt(.5);function wr(e){return Math.floor((Math.pow(8,e+1)-1)/7)}function rt(e){return Math.floor((Math.pow(8,e)-1)/7)}var Bt=4,zt=65535,_r=class{constructor(e,t=Mr){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=t,this.totalCells=wr(t);let n=this.device,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST;this.cellsBuffer=n.createBuffer({label:"oct-cells",size:this.totalCells*Bt*4,usage:i}),this.boundsBuffer=n.createBuffer({label:"oct-bounds",size:32,usage:i}),this.levelOffsetsBuffer=n.createBuffer({label:"oct-level-offsets",size:(t+1)*4,usage:i});let o=new Uint32Array(t+1);for(let f=0;f<=t;f++)o[f]=rt(f);n.queue.writeBuffer(this.levelOffsetsBuffer,0,o),this.boundsParamsBuf=n.createBuffer({label:"oct-bounds-params",size:16,usage:r}),this.clearParamsBuf=n.createBuffer({label:"oct-clear-params",size:16,usage:r}),this.binParamsBuf=n.createBuffer({label:"oct-bin-params",size:16,usage:r}),this.traverseParamsBuf=n.createBuffer({label:"oct-traverse-params",size:48,usage:r});for(let f=0;f<t;f++){let p=n.createBuffer({label:`oct-accum-params-L${f}`,size:16,usage:r}),g=new ArrayBuffer(16),m=new Uint32Array(g);m[0]=rt(f),m[1]=rt(f+1),m[2]=Math.pow(8,f),n.queue.writeBuffer(p,0,g),this.accumParamsBufs.push(p)}let a=this.totalCells*Bt,s=Math.ceil(a/Pt),u=Math.min(s,zt)*Pt;n.queue.writeBuffer(this.clearParamsBuf,0,new Uint32Array([a,u,0,0]));let c=(f,p)=>n.createShaderModule({label:f,code:p}),d=(f,p,g="main")=>n.createComputePipeline({label:f,layout:"auto",compute:{module:p,entryPoint:g}});this.boundsPipeline=d("oct-bounds-pipe",c("oct-bounds",Et)),this.clearPipeline=d("oct-clear-pipe",c("oct-clear",$n)),this.binPipeline=d("oct-bin-pipe",c("oct-bin",vr)),this.accumPipeline=d("oct-accum-pipe",c("oct-accum",xr)),this.traversePipeline=d("oct-traverse-pipe",c("oct-traverse",br)),this.bindAll(e)}bindAll(e){let t=this.device;this.boundsBG=t.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=t.createBindGroup({layout:this.clearPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.clearParamsBuf}}]}),this.binBG=t.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 i=0;i<this.maxLevel;i++)this.accumBGs.push(t.createBindGroup({layout:this.accumPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.accumParamsBufs[i]}}]}));this.traverseBG=t.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}}]}),t.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]));let n=new ArrayBuffer(16);new Uint32Array(n,0,3).set([this.nodeCount,this.maxLevel,rt(this.maxLevel)]),new Float32Array(n,12,1)[0]=kn,t.queue.writeBuffer(this.binParamsBuf,0,n)}setConfig(e){Object.assign(this.config,e)}apply(e,t){let n=this.device,i=this.nodeCount,r=Pt,o=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);n.queue.writeBuffer(this.boundsBuffer,0,o),this.run(t,this.boundsPipeline,this.boundsBG,Math.ceil(i/r),"oct-p1-bounds");let a=Math.ceil(this.totalCells*Bt/r),s=Math.min(a,zt),l=Math.ceil(a/zt);this.run2D(t,this.clearPipeline,this.clearBG,s,l,"oct-p2-clear"),this.run(t,this.binPipeline,this.binBG,Math.ceil(i/r),"oct-p3-bin");for(let f=this.maxLevel-1;f>=0;f--)this.run(t,this.accumPipeline,this.accumBGs[f],Math.ceil(Math.pow(8,f)/r),`oct-p4-accum-L${f}`);let u=new ArrayBuffer(48),c=new Uint32Array(u),d=new Float32Array(u);c[0]=i,c[1]=this.maxLevel,d[4]=this.config.strength,d[5]=e,d[6]=this.config.theta*this.config.theta,d[7]=this.config.distanceMin*this.config.distanceMin,d[8]=this.config.distanceMax===1/0?1e30:this.config.distanceMax*this.config.distanceMax,d[9]=kn,n.queue.writeBuffer(this.traverseParamsBuf,0,u),this.run(t,this.traversePipeline,this.traverseBG,Math.ceil(i/r),"oct-p5-traverse")}run(e,t,n,i,r){let o=e.beginComputePass({label:r});o.setPipeline(t),o.setBindGroup(0,n),o.dispatchWorkgroups(i),o.end()}run2D(e,t,n,i,r,o){let a=e.beginComputePass({label:o});a.setPipeline(t),a.setBindGroup(0,n),a.dispatchWorkgroups(i,r,1),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 Sr(){let e=-30,t=1,n=1/0,i=.9,r=null,o={initialize(a,s,l){},initGPU(a){r?.dispose(),r=new _r(a),r.setConfig({strength:e,theta:i,distanceMin:t,distanceMax:n})},apply(a,s){r?.apply(a,s)},dispose(){r?.dispose(),r=null},strength(a){return arguments.length===0?e:(e=+a,r?.setConfig({strength:e}),o)},distanceMin(a){return arguments.length===0?t:(t=+a,r?.setConfig({distanceMin:t}),o)},distanceMax(a){return arguments.length===0?n:(n=+a,r?.setConfig({distanceMax:n}),o)},theta(a){return arguments.length===0?i:(i=+a,r?.setConfig({theta:i}),o)}};return o}var Tr={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},$e=240;function Pr(e,t,n){let i=globalThis,r=i.__webgpuPathATiming;r||(r={tick:new Float32Array($e),read:new Float32Array($e),sync:new Float32Array($e),i:0,filled:0,reset(){this.i=0,this.filled=0},summary(){let o=this.filled;if(o===0)return null;let a=s=>{let l=0,u=1/0,c=-1/0;for(let d=0;d<o;d++){let f=s[d];l+=f,f<u&&(u=f),f>c&&(c=f)}return{mean:+(l/o).toFixed(3),min:+u.toFixed(3),max:+c.toFixed(3),n:o}};return{skipFlag:!!globalThis.__webgpuPathASkip,tickMs:a(this.tick),readMs:a(this.read),syncMs:a(this.sync),totalMs:{mean:+(this.tick.reduce((s,l)=>s+l,0)/o+this.read.reduce((s,l)=>s+l,0)/o+this.sync.reduce((s,l)=>s+l,0)/o).toFixed(3)}}}},i.__webgpuPathATiming=r),r.tick[r.i]=e,r.read[r.i]=t,r.sync[r.i]=n,r.i=(r.i+1)%$e,r.filled<$e&&r.filled++}var ot=class{constructor(e,t,n={}){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=i=>{let r=i.source,o=i.target,a=Math.min(this._linkDegree[r]??1,this._linkDegree[o]??1);return this.params.linkStrength*(a>0?1/a:1)},this._readbackTickCounter=0,!Pe())throw new Error("[WebGPUForceLayoutController] navigator.gpu unavailable in this environment. Use the WebGL-backed GPUForceLayoutController instead.");this.params={...Tr},this.options=n,this.graph=e??{layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!0}}setReadbackTimingSink(e){return this._readbackTimingSink=e,this}config(e){this.getOptions=e;let t=e();return t&&this.applyConfig(t),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,t=0,n=!1){let i=this.params.dimensions,r=this.getOptions();r&&this.applyConfig(r),this.params.dimensions=i,this.disposeSimulation(),this.buildSimulation(n),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 i=this.params.dimensions;this.applyConfig(e),this.params.dimensions=i}this.applyForceParams();let t=this.graph.layoutNodes.length,n=this.simNodes.length;this.simulation&&t===n?(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 t=this.graph.layoutNodes,n=this.graph.layoutEdges,i=t.length;if(i===0)return;let r=this.params.dimensions,o=t.some(m=>Math.abs(m.position.z)>1e-6),a=r>2&&!o&&!e,s=Math.cbrt(t.length)*2,u=Math.min(10,Math.pow(2,29)/(Math.pow(i,1.5)*64)),c=r===2&&!a&&!e,d=Math.PI*(3-Math.sqrt(5));this.simNodes=t.map((m,y)=>{let M={id:m.id,index:y};if(m.pinned)M.fx=m.position.x,M.fy=m.position.y,M.fz=m.position.z,M.x=m.position.x,M.y=m.position.y,M.z=m.position.z;else if(a){let S=Math.random(),h=Math.random(),v=Math.random(),b=2*Math.PI*S,x=Math.acos(2*h-1),E=Math.cbrt(v)*s;M.x=E*Math.sin(x)*Math.cos(b),M.y=E*Math.sin(x)*Math.sin(b),M.z=E*Math.cos(x)}else if(c){let S=u*Math.sqrt(.5+y),h=y*d;M.x=S*Math.cos(h),M.y=S*Math.sin(h),M.z=0}else e&&(M.x=m.position.x,M.y=m.position.y,M.z=r<=2?0:m.position.z);return M}),this.nodeIdToIndex.clear();for(let m=0;m<i;m++)this.nodeIdToIndex.set(this.simNodes[m].id,m*3);this.sharedArray=new Float32Array(i*3),this._currentSpaceSize=Math.max(10,2*(this.params.dimensions===2?10*Math.sqrt(i):10*Math.cbrt(i)));let f=Ln(this.simNodes,this.params.dimensions,{device:this.options.device});f.alpha(this.params.alpha).alphaDecay(this.params.alphaDecay).velocityDecay(this.params.velocityDecay).alphaTarget(0).maxVel(this.staticMaxVel(this.simNodes.length));let{forcexy:p,forcez:g}=this.calculateAxisForces();if(this.forceXInstance=Nn(0).strength(p*this.params.gravityX),this.forceYInstance=qn(0).strength(p*this.params.gravityY),f.force("x",this.forceXInstance),f.force("y",this.forceYInstance),this.params.dimensions>2&&(this.forceZInstance=On(0).strength(g*this.params.gravityZ),f.force("z",this.forceZInstance)),this.forceCharge=this.makeChargeForce(i),f.force("charge",this.forceCharge),n.length){let m=n.map(M=>{let S=this.nodeIdToIndex.get(M.sourceId),h=this.nodeIdToIndex.get(M.targetId);return S===void 0||h===void 0?null:{id:M.id,source:S/3,target:h/3}}).filter(M=>M!==null),y=m.length;this._linkDegree=new Int32Array(i);for(let M=0;M<y;M++)this._linkDegree[m[M].source]++,this._linkDegree[m[M].target]++;this.forceLinkInstance=Hn(m).strength(this._linkStrengthFn).distance(this.params.linkDistance),f.force("link",this.forceLinkInstance)}this.forceCenterInstance=Gn(0,0,0).strength(1),f.force("center",this.forceCenterInstance),this.simulation=f}makeChargeForce(e){if(this.params.dimensions===2){let n=yr();return n.theta?.(this.params.octreeTheta),n.strength(this.params.charge),n}if(e>=1e4){let n=Yn();return n.theta(this.params.octreeTheta),n.strength(this.params.charge),n}let t=Sr();return t.theta?.(this.params.octreeTheta),t.strength(this.params.charge),t}calculateAxisForces(){let e,t;if(this.params.dimensions===2)e=this.params.gravity*1.5,t=0;else{let n=this.params.heightCompress;t=Math.min(10,this.params.gravity*Math.sqrt(n)),e=this.params.gravity/Math.sqrt(n)}return{forcexy:e,forcez:t}}applyForceParams(){if(!this.simulation)return;this.simulation.alphaDecay(this.params.alphaDecay),this.simulation.velocityDecay(this.params.velocityDecay);let{forcexy:e,forcez:t}=this.calculateAxisForces();this.forceXInstance?.strength(e*this.params.gravityX),this.forceYInstance?.strength(e*this.params.gravityY),this.forceZInstance?.strength(t*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 t=this.options.onTick;if(t)try{t({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(t=>e.on("ready",()=>t()));this._enable&&this.simulation&&(await this.waitForFrame(),!!this._enable);){let t=this.simulation;if(!t)break;let n=performance.now();t.tick(1),this.afterTick(t);let i=performance.now(),r=Math.max(1,Math.floor(globalThis.__webgpuReadbackInterval??1));this._readbackTickCounter++;let o=this._readbackTickCounter>=r,a=t.alpha()<t.alphaMin(),s=o||a,l=i,u=i;if(s){this._readbackTickCounter=0;try{await t.readPositions()}catch(c){console.warn("[WebGPUForceLayoutController] readPositions threw, skipping:",c);continue}if(t!==this.simulation||!this._enable)break;l=performance.now(),this.syncPositionsToSharedArray(),u=performance.now(),this.graph.renderNeedsUpdate=!0}if(Pr(i-n,l-i,u-l),s&&this._readbackTimingSink)try{this._readbackTimingSink(u-i)}catch{}if(a){this.isFinish=!0,this.graph.renderNeedsUpdate=!1;break}}}finally{this._loopRunning=!1}}}waitForFrame(){return new Promise(e=>requestAnimationFrame(()=>e()))}syncPositionsToSharedArray(){let e=this.sharedArray,t=this.graph.layoutNodes,n=this.simNodes,i=Math.min(e.length/3,n.length,t.length);if(globalThis.__webgpuPathASkip===!0){let o=0;for(let a=0;a<e.length;a++){let s=e[a],l=s<0?-s:s;l>o&&(o=l)}this._currentSpaceSize=Math.max(10,2*o);return}let r=0;for(let o=0;o<i;o++){let a=n[o],s=a.x??0,l=a.y??0,u=a.z??0;e[o*3]=s,e[o*3+1]=l,e[o*3+2]=u;let c=t[o];c?.position&&(c.position.x=s,c.position.y=l,c.position.z=u);let d=Math.max(Math.abs(s),Math.abs(l),Math.abs(u));d>r&&(r=d)}this._currentSpaceSize=Math.max(10,2*r)}staticMaxVel(e){let t=this.params.dimensions===2?Math.max(10,Math.sqrt(e)*.5):Math.max(10,Math.cbrt(e)*2);return Math.min(2,t*.1)}updateLayoutOption(e,t){if(e==="friction"?this.params.velocityDecay=t:this.params[e]=t,!this.simulation||!this._enable)return;let n=()=>{this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop()};switch(e){case"charge":this.forceCharge?.strength(t),n();break;case"linkDistance":this.forceLinkInstance?.distance(t),n();break;case"linkStrength":this.forceLinkInstance?.strength(this._linkStrengthFn),n();break;case"gravity":case"gravityX":case"gravityY":case"gravityZ":case"heightCompress":{let{forcexy:i,forcez:r}=this.calculateAxisForces();this.forceXInstance?.strength(i*this.params.gravityX),this.forceYInstance?.strength(i*this.params.gravityY),this.forceZInstance?.strength(r*this.params.gravityZ),n();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(t=>{let n=this.nodeIdToIndex.get(t.id);if(n===void 0)return;let i=n/3,r=this.simNodes[i];r&&(t.pinned?(r.fx=t.position.x,r.fy=t.position.y,r.fz=t.position.z,r.x=t.position.x,r.y=t.position.y,r.z=t.position.z,this.simulation.uploadPosition(i,t.position.x,t.position.y,t.position.z),this.simulation.uploadPinned(i,!0)):(delete r.fx,delete r.fy,delete r.fz,this.simulation.uploadPinned(i,!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(t=>{let n=this.nodeIdToIndex.get(t);if(n===void 0)return;let i=n/3,r=this.simNodes[i];r&&(delete r.fx,delete r.fy,delete r.fz,this.simulation.uploadPinned(i,!1))}),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop(),this.graph.renderNeedsUpdate=!0)}transitionDimensions(e,t=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,t=this.graph.layoutNodes;for(let n=0;n<this.simNodes.length;n++){let i=this.simNodes[n],r=t[n];!r||!r.position||(r.position.x=i.x??0,r.position.y=i.y??0,r.position.z=e>2?i.z??0:0)}}setExpectedNodeCount(e){}clearExpectedNodeCount(){}updateGraph(e,t,n=!1){this.graph.layoutNodes=e,this.graph.layoutEdges=t}},st=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,t){this.c.transitionDimensions(e,t)}getDimensions(){return this.c.getDimensions()}updateOption(e,t){this.c.updateLayoutOption(e,t)}};var ue=pe(require("three"),1);var Q=pe(require("three"),1),Fe=pe(require("three"),1),$=pe(require("three"),1),Z=pe(require("three"),1),ne=pe(require("three"),1),Ie=pe(require("three"),1),ae=pe(require("three"),1),oe=pe(require("three"),1),se=pe(require("three"),1),De=pe(require("three"),1),jn=pe(require("three"),1),he=`/**
|
|
1426
|
+
`,qr=7,Ft=64,Yn=64,uo=Math.sqrt(.5);function Or(e){return Math.floor((Math.pow(8,e+1)-1)/7)}function ct(e){return Math.floor((Math.pow(8,e)-1)/7)}var It=4,Dt=65535,Hr=class{constructor(e,t=qr){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=t,this.totalCells=Or(t);let n=this.device,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST;this.cellsBuffer=n.createBuffer({label:"oct-cells",size:this.totalCells*It*4,usage:i}),this.boundsBuffer=n.createBuffer({label:"oct-bounds",size:32,usage:i}),this.levelOffsetsBuffer=n.createBuffer({label:"oct-level-offsets",size:(t+1)*4,usage:i});let o=new Uint32Array(t+1);for(let d=0;d<=t;d++)o[d]=ct(d);n.queue.writeBuffer(this.levelOffsetsBuffer,0,o),this.boundsParamsBuf=n.createBuffer({label:"oct-bounds-params",size:16,usage:r}),this.clearParamsBuf=n.createBuffer({label:"oct-clear-params",size:16,usage:r}),this.binParamsBuf=n.createBuffer({label:"oct-bin-params",size:16,usage:r}),this.traverseParamsBuf=n.createBuffer({label:"oct-traverse-params",size:48,usage:r});for(let d=0;d<t;d++){let p=n.createBuffer({label:`oct-accum-params-L${d}`,size:16,usage:r}),m=new ArrayBuffer(16),g=new Uint32Array(m);g[0]=ct(d),g[1]=ct(d+1),g[2]=Math.pow(8,d),n.queue.writeBuffer(p,0,m),this.accumParamsBufs.push(p)}let a=this.totalCells*It,s=Math.ceil(a/Ft),u=Math.min(s,Dt)*Ft;n.queue.writeBuffer(this.clearParamsBuf,0,new Uint32Array([a,u,0,0]));let c=(d,p)=>n.createShaderModule({label:d,code:p}),f=(d,p,m="main")=>n.createComputePipeline({label:d,layout:"auto",compute:{module:p,entryPoint:m}});this.boundsPipeline=f("oct-bounds-pipe",c("oct-bounds",Ut)),this.clearPipeline=f("oct-clear-pipe",c("oct-clear",si)),this.binPipeline=f("oct-bin-pipe",c("oct-bin",Lr)),this.accumPipeline=f("oct-accum-pipe",c("oct-accum",Gr)),this.traversePipeline=f("oct-traverse-pipe",c("oct-traverse",Nr)),this.bindAll(e)}bindAll(e){let t=this.device;this.boundsBG=t.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=t.createBindGroup({layout:this.clearPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.clearParamsBuf}}]}),this.binBG=t.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 i=0;i<this.maxLevel;i++)this.accumBGs.push(t.createBindGroup({layout:this.accumPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.accumParamsBufs[i]}}]}));this.traverseBG=t.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}}]}),t.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]));let n=new ArrayBuffer(16);new Uint32Array(n,0,3).set([this.nodeCount,this.maxLevel,ct(this.maxLevel)]),new Float32Array(n,12,1)[0]=Yn,t.queue.writeBuffer(this.binParamsBuf,0,n)}setConfig(e){Object.assign(this.config,e)}apply(e,t){let n=this.device,i=this.nodeCount,r=Ft,o=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);n.queue.writeBuffer(this.boundsBuffer,0,o),this.run(t,this.boundsPipeline,this.boundsBG,Math.ceil(i/r),"oct-p1-bounds");let a=Math.ceil(this.totalCells*It/r),s=Math.min(a,Dt),l=Math.ceil(a/Dt);this.run2D(t,this.clearPipeline,this.clearBG,s,l,"oct-p2-clear"),this.run(t,this.binPipeline,this.binBG,Math.ceil(i/r),"oct-p3-bin");for(let d=this.maxLevel-1;d>=0;d--)this.run(t,this.accumPipeline,this.accumBGs[d],Math.ceil(Math.pow(8,d)/r),`oct-p4-accum-L${d}`);let u=new ArrayBuffer(48),c=new Uint32Array(u),f=new Float32Array(u);c[0]=i,c[1]=this.maxLevel,f[4]=this.config.strength,f[5]=e,f[6]=this.config.theta*this.config.theta,f[7]=this.config.distanceMin*this.config.distanceMin,f[8]=this.config.distanceMax===1/0?1e30:this.config.distanceMax*this.config.distanceMax,f[9]=Yn,n.queue.writeBuffer(this.traverseParamsBuf,0,u),this.run(t,this.traversePipeline,this.traverseBG,Math.ceil(i/r),"oct-p5-traverse")}run(e,t,n,i,r){let o=e.beginComputePass({label:r});o.setPipeline(t),o.setBindGroup(0,n),o.dispatchWorkgroups(i),o.end()}run2D(e,t,n,i,r,o){let a=e.beginComputePass({label:o});a.setPipeline(t),a.setBindGroup(0,n),a.dispatchWorkgroups(i,r,1),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 Xr(){let e=-30,t=1,n=1/0,i=.9,r=null,o={initialize(a,s,l){},initGPU(a){r?.dispose(),r=new Hr(a),r.setConfig({strength:e,theta:i,distanceMin:t,distanceMax:n})},apply(a,s){r?.apply(a,s)},dispose(){r?.dispose(),r=null},strength(a){return arguments.length===0?e:(e=+a,r?.setConfig({strength:e}),o)},distanceMin(a){return arguments.length===0?t:(t=+a,r?.setConfig({distanceMin:t}),o)},distanceMax(a){return arguments.length===0?n:(n=+a,r?.setConfig({distanceMax:n}),o)},theta(a){return arguments.length===0?i:(i=+a,r?.setConfig({theta:i}),o)}};return o}var Yr={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},je=240;function $r(e,t,n){let i=globalThis,r=i.__webgpuPathATiming;r||(r={tick:new Float32Array(je),read:new Float32Array(je),sync:new Float32Array(je),i:0,filled:0,reset(){this.i=0,this.filled=0},summary(){let o=this.filled;if(o===0)return null;let a=s=>{let l=0,u=1/0,c=-1/0;for(let f=0;f<o;f++){let d=s[f];l+=d,d<u&&(u=d),d>c&&(c=d)}return{mean:+(l/o).toFixed(3),min:+u.toFixed(3),max:+c.toFixed(3),n:o}};return{skipFlag:!!globalThis.__webgpuPathASkip,tickMs:a(this.tick),readMs:a(this.read),syncMs:a(this.sync),totalMs:{mean:+(this.tick.reduce((s,l)=>s+l,0)/o+this.read.reduce((s,l)=>s+l,0)/o+this.sync.reduce((s,l)=>s+l,0)/o).toFixed(3)}}}},i.__webgpuPathATiming=r),r.tick[r.i]=e,r.read[r.i]=t,r.sync[r.i]=n,r.i=(r.i+1)%je,r.filled<je&&r.filled++}var ft=class{constructor(e,t,n={}){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=i=>{let r=i.source,o=i.target,a=Math.min(this._linkDegree[r]??1,this._linkDegree[o]??1);return this.params.linkStrength*(a>0?1/a:1)},this._readbackTickCounter=0,!Pe())throw new Error("[WebGPUForceLayoutController] navigator.gpu unavailable in this environment. Use the WebGL-backed GPUForceLayoutController instead.");this.params={...Yr},this.options=n,this.graph=e??{layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!0}}setReadbackTimingSink(e){return this._readbackTimingSink=e,this}config(e){this.getOptions=e;let t=e();return t&&this.applyConfig(t),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,t=0,n=!1){let i=this.params.dimensions,r=this.getOptions();r&&this.applyConfig(r),this.params.dimensions=i,this.disposeSimulation(),this.buildSimulation(n),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 i=this.params.dimensions;this.applyConfig(e),this.params.dimensions=i}this.applyForceParams();let t=this.graph.layoutNodes.length,n=this.simNodes.length;this.simulation&&t===n?(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 t=this.graph.layoutNodes,n=this.graph.layoutEdges,i=t.length;if(i===0)return;let r=this.params.dimensions,o=t.some(g=>Math.abs(g.position.z)>1e-6),a=r>2&&!o&&!e,s=Math.cbrt(t.length)*2,u=Math.min(10,Math.pow(2,29)/(Math.pow(i,1.5)*64)),c=r===2&&!a&&!e,f=Math.PI*(3-Math.sqrt(5));this.simNodes=t.map((g,y)=>{let w={id:g.id,index:y};if(g.pinned)w.fx=g.position.x,w.fy=g.position.y,w.fz=g.position.z,w.x=g.position.x,w.y=g.position.y,w.z=g.position.z;else if(a){let M=Math.random(),h=Math.random(),v=Math.random(),b=2*Math.PI*M,x=Math.acos(2*h-1),C=Math.cbrt(v)*s;w.x=C*Math.sin(x)*Math.cos(b),w.y=C*Math.sin(x)*Math.sin(b),w.z=C*Math.cos(x)}else if(c){let M=u*Math.sqrt(.5+y),h=y*f;w.x=M*Math.cos(h),w.y=M*Math.sin(h),w.z=0}else e&&(w.x=g.position.x,w.y=g.position.y,w.z=r<=2?0:g.position.z);return w}),this.nodeIdToIndex.clear();for(let g=0;g<i;g++)this.nodeIdToIndex.set(this.simNodes[g].id,g*3);this.sharedArray=new Float32Array(i*3),this._currentSpaceSize=Math.max(10,2*(this.params.dimensions===2?10*Math.sqrt(i):10*Math.cbrt(i)));let d=Jn(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:p,forcez:m}=this.calculateAxisForces();if(this.forceXInstance=ti(0).strength(p*this.params.gravityX),this.forceYInstance=ni(0).strength(p*this.params.gravityY),d.force("x",this.forceXInstance),d.force("y",this.forceYInstance),this.params.dimensions>2&&(this.forceZInstance=ii(0).strength(m*this.params.gravityZ),d.force("z",this.forceZInstance)),this.forceCharge=this.makeChargeForce(i),d.force("charge",this.forceCharge),n.length){let g=n.map(w=>{let M=this.nodeIdToIndex.get(w.sourceId),h=this.nodeIdToIndex.get(w.targetId);return M===void 0||h===void 0?null:{id:w.id,source:M/3,target:h/3}}).filter(w=>w!==null),y=g.length;this._linkDegree=new Int32Array(i);for(let w=0;w<y;w++)this._linkDegree[g[w].source]++,this._linkDegree[g[w].target]++;this.forceLinkInstance=ri(g).strength(this._linkStrengthFn).distance(this.params.linkDistance),d.force("link",this.forceLinkInstance)}this.forceCenterInstance=ei(0,0,0).strength(1),d.force("center",this.forceCenterInstance),this.simulation=d}makeChargeForce(e){if(this.params.dimensions===2){let n=Ur();return n.theta?.(this.params.octreeTheta),n.strength(this.params.charge),n}if(e>=1e4){let n=oi();return n.theta(this.params.octreeTheta),n.strength(this.params.charge),n}let t=Xr();return t.theta?.(this.params.octreeTheta),t.strength(this.params.charge),t}calculateAxisForces(){let e,t;if(this.params.dimensions===2)e=this.params.gravity*1.5,t=0;else{let n=this.params.heightCompress;t=Math.min(10,this.params.gravity*Math.sqrt(n)),e=this.params.gravity/Math.sqrt(n)}return{forcexy:e,forcez:t}}applyForceParams(){if(!this.simulation)return;this.simulation.alphaDecay(this.params.alphaDecay),this.simulation.velocityDecay(this.params.velocityDecay);let{forcexy:e,forcez:t}=this.calculateAxisForces();this.forceXInstance?.strength(e*this.params.gravityX),this.forceYInstance?.strength(e*this.params.gravityY),this.forceZInstance?.strength(t*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 t=this.options.onTick;if(t)try{t({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(t=>e.on("ready",()=>t()));this._enable&&this.simulation&&(await this.waitForFrame(),!!this._enable);){let t=this.simulation;if(!t)break;let n=performance.now();t.tick(1),this.afterTick(t);let i=performance.now(),r=Math.max(1,Math.floor(globalThis.__webgpuReadbackInterval??1));this._readbackTickCounter++;let o=this._readbackTickCounter>=r,a=t.alpha()<t.alphaMin(),s=o||a,l=i,u=i;if(s){this._readbackTickCounter=0;try{await t.readPositions()}catch(c){console.warn("[WebGPUForceLayoutController] readPositions threw, skipping:",c);continue}if(t!==this.simulation||!this._enable)break;l=performance.now(),this.syncPositionsToSharedArray(),u=performance.now(),this.graph.renderNeedsUpdate=!0}if($r(i-n,l-i,u-l),s&&this._readbackTimingSink)try{this._readbackTimingSink(u-i)}catch{}if(a){this.isFinish=!0,this.graph.renderNeedsUpdate=!1;break}}}finally{this._loopRunning=!1}}}waitForFrame(){return new Promise(e=>requestAnimationFrame(()=>e()))}syncPositionsToSharedArray(){let e=this.sharedArray,t=this.graph.layoutNodes,n=this.simNodes,i=Math.min(e.length/3,n.length,t.length);if(globalThis.__webgpuPathASkip===!0){let o=0;for(let a=0;a<e.length;a++){let s=e[a],l=s<0?-s:s;l>o&&(o=l)}this._currentSpaceSize=Math.max(10,2*o);return}let r=0;for(let o=0;o<i;o++){let a=n[o],s=a.x??0,l=a.y??0,u=a.z??0;e[o*3]=s,e[o*3+1]=l,e[o*3+2]=u;let c=t[o];c?.position&&(c.position.x=s,c.position.y=l,c.position.z=u);let f=Math.max(Math.abs(s),Math.abs(l),Math.abs(u));f>r&&(r=f)}this._currentSpaceSize=Math.max(10,2*r)}staticMaxVel(e){let t=this.params.dimensions===2?Math.max(10,Math.sqrt(e)*.5):Math.max(10,Math.cbrt(e)*2);return Math.min(2,t*.1)}updateLayoutOption(e,t){if(e==="friction"?this.params.velocityDecay=t:this.params[e]=t,!this.simulation||!this._enable)return;let n=()=>{this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop()};switch(e){case"charge":this.forceCharge?.strength(t),n();break;case"linkDistance":this.forceLinkInstance?.distance(t),n();break;case"linkStrength":this.forceLinkInstance?.strength(this._linkStrengthFn),n();break;case"gravity":case"gravityX":case"gravityY":case"gravityZ":case"heightCompress":{let{forcexy:i,forcez:r}=this.calculateAxisForces();this.forceXInstance?.strength(i*this.params.gravityX),this.forceYInstance?.strength(i*this.params.gravityY),this.forceZInstance?.strength(r*this.params.gravityZ),n();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(t=>{let n=this.nodeIdToIndex.get(t.id);if(n===void 0)return;let i=n/3,r=this.simNodes[i];r&&(t.pinned?(r.fx=t.position.x,r.fy=t.position.y,r.fz=t.position.z,r.x=t.position.x,r.y=t.position.y,r.z=t.position.z,this.simulation.uploadPosition(i,t.position.x,t.position.y,t.position.z),this.simulation.uploadPinned(i,!0)):(delete r.fx,delete r.fy,delete r.fz,this.simulation.uploadPinned(i,!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(t=>{let n=this.nodeIdToIndex.get(t);if(n===void 0)return;let i=n/3,r=this.simNodes[i];r&&(delete r.fx,delete r.fy,delete r.fz,this.simulation.uploadPinned(i,!1))}),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop(),this.graph.renderNeedsUpdate=!0)}transitionDimensions(e,t=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,t=this.graph.layoutNodes;for(let n=0;n<this.simNodes.length;n++){let i=this.simNodes[n],r=t[n];!r||!r.position||(r.position.x=i.x??0,r.position.y=i.y??0,r.position.z=e>2?i.z??0:0)}}setExpectedNodeCount(e){}clearExpectedNodeCount(){}updateGraph(e,t,n=!1){this.graph.layoutNodes=e,this.graph.layoutEdges=t}},pt=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,t){this.c.transitionDimensions(e,t)}getDimensions(){return this.c.getDimensions()}updateOption(e,t){this.c.updateLayoutOption(e,t)}};var ue=pe(require("three"),1);var Q=pe(require("three"),1),Fe=pe(require("three"),1),$=pe(require("three"),1),Z=pe(require("three"),1),ne=pe(require("three"),1),Ie=pe(require("three"),1),ae=pe(require("three"),1),oe=pe(require("three"),1),se=pe(require("three"),1),De=pe(require("three"),1),ui=pe(require("three"),1),he=`/**
|
|
1427
1427
|
* Simple vertex shader for full-screen quad rendering
|
|
1428
1428
|
* Used by all GPU compute passes
|
|
1429
1429
|
*/
|
|
@@ -1433,7 +1433,7 @@ void main() {
|
|
|
1433
1433
|
vUv = uv;
|
|
1434
1434
|
gl_Position = vec4(position, 1.0);
|
|
1435
1435
|
}
|
|
1436
|
-
`,
|
|
1436
|
+
`,Zr=`/**
|
|
1437
1437
|
* Position update shader
|
|
1438
1438
|
*
|
|
1439
1439
|
* Applies accumulated velocity to position, with:
|
|
@@ -1493,7 +1493,7 @@ void main() {
|
|
|
1493
1493
|
|
|
1494
1494
|
gl_FragColor = vec4(newPos, pos.w);
|
|
1495
1495
|
}
|
|
1496
|
-
`,
|
|
1496
|
+
`,li=`/**
|
|
1497
1497
|
* Clear shader - outputs zero for all fragments
|
|
1498
1498
|
* Used to reset velocity buffer at the start of each tick
|
|
1499
1499
|
*
|
|
@@ -1506,7 +1506,7 @@ precision highp float;
|
|
|
1506
1506
|
void main() {
|
|
1507
1507
|
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
|
|
1508
1508
|
}
|
|
1509
|
-
`,
|
|
1509
|
+
`,jr=`/**
|
|
1510
1510
|
* Copy shader - copies one texture to another
|
|
1511
1511
|
* Used for initializing FBOs with data textures
|
|
1512
1512
|
*/
|
|
@@ -1518,7 +1518,7 @@ varying vec2 vUv;
|
|
|
1518
1518
|
void main() {
|
|
1519
1519
|
gl_FragColor = texture2D(sourceTexture, vUv);
|
|
1520
1520
|
}
|
|
1521
|
-
`,
|
|
1521
|
+
`,Vr=`/**
|
|
1522
1522
|
* Velocity decay shader
|
|
1523
1523
|
*
|
|
1524
1524
|
* Applies velocity decay (friction) to existing velocity.
|
|
@@ -1542,7 +1542,7 @@ void main() {
|
|
|
1542
1542
|
|
|
1543
1543
|
gl_FragColor = vec4(vel.xyz, 1.0);
|
|
1544
1544
|
}
|
|
1545
|
-
`,
|
|
1545
|
+
`,Wr=3;function Kr(e,t,n){let i=Math.min(Wr,Math.max(1,Math.round(t||3))),r,o=1,a=.001,s=1-Math.pow(a,1/300),l=0,u=.6,c=jn(),f=new Map,d=null,p=_t("tick","end");e==null&&(e=[]);let m,g,y,w,M=!1,h=0,v=0,b=null,x=null,C=0,E=null,A=null,R=0,I=null,L=null,B=null,F=null,_=null,z=null,P=null,T=null,k=1e3/10,q=0,N=!1;function G(){if(M)return;if(n)m=n;else{let H=document.createElement("canvas");H.style.display="none",m=new ue.WebGLRenderer({canvas:H,alpha:!0,antialias:!1}),m.setSize(256,256)}g=new ue.Scene,y=new ue.OrthographicCamera(-1,1,1,-1,0,1);let U=ye();_=new ue.ShaderMaterial({uniforms:{},vertexShader:he,fragmentShader:li,blending:ue.NoBlending,depthTest:!1,depthWrite:!1}),z=new ue.ShaderMaterial({uniforms:{sourceTexture:{value:null}},vertexShader:he,fragmentShader:jr,depthTest:!1,depthWrite:!1}),F=new ue.ShaderMaterial({uniforms:{positionTexture:{value:null},velocityTexture:{value:null},pinnedTexture:{value:null},friction:{value:1},spaceSize:{value:10},nDim:{value:i}},vertexShader:he,fragmentShader:Zr,depthTest:!1,depthWrite:!1}),P=new ue.ShaderMaterial({uniforms:{velocityTexture:{value:null},decay:{value:u}},vertexShader:he,fragmentShader:Vr,depthTest:!1,depthWrite:!1}),w=new ue.Mesh(U,_),g.add(w),M=!0}function S(){if(M||G(),v=e.length,v===0)return;h=At(v);let U=qe(v,i),H=m.getContext(),K=H.getParameter(H.MAX_TEXTURE_SIZE);b?.dispose(),x?.dispose(),E?.dispose(),A?.dispose(),I?.dispose(),L?.dispose(),B?.dispose(),b=Ee(h),x=Ee(h),E=Ee(h),A=Ee(h),I=Ee(h),C=0,R=0;let le=Vn(e,h),J=Oe(le,h),ve=Wn(e,h),me=Oe(ve,h),fe=Kn(e,h);L=Oe(fe,h);let ee=h*h,we=new Float32Array(ee*4);for(let ge=0;ge<ee;ge++)we[ge*4]=(c()-.5)*2,we[ge*4+1]=(c()-.5)*2,we[ge*4+2]=(c()-.5)*2,we[ge*4+3]=c();B=Oe(we,h),z.uniforms.sourceTexture.value=J,w.material=z,m.setRenderTarget(b),m.render(g,y),m.setRenderTarget(x),m.render(g,y),z.uniforms.sourceTexture.value=me,m.setRenderTarget(E),m.render(g,y),m.setRenderTarget(A),m.render(g,y),w.material=_,m.setRenderTarget(I),m.render(g,y),m.setRenderTarget(null),J.dispose(),me.dispose(),F.uniforms.spaceSize.value=U;let We={renderer:m,scene:g,camera:y,textureSize:h,nodeCount:v};f.forEach(ge=>{if(ge.initGPU)try{ge.initGPU(We)}catch{}})}function D(){return C===0?b:x}function O(){return C===0?x:b}function Y(){C=1-C}function X(){return R===0?E:A}function W(){return R===0?A:E}function V(){R=1-R}function ce(){j(),p.call("tick",r),o<a&&(d?.stop(),p.call("end",r))}function j(U){U===void 0&&(U=1);for(let H=0;H<U;H++)o+=(l-o)*s,M&&v>0?Be():mt();return r}let de=0,ie=0;function Be(){de++;let U=performance.now();(de%50===0||U-ie>2e3)&&(ie=U);let H=O(),K=D(),le=W(),J=X(),ve=qe(v,i);for(let[,ee]of f)if(typeof ee.getSpaceSize=="function"){ve=ee.getSpaceSize();break}let me=ve;z.uniforms.sourceTexture.value=le.texture,w.material=z,m.setRenderTarget(I),m.render(g,y),f.forEach(ee=>{try{ee.apply(o,H.texture,I)}catch{}}),P.uniforms.velocityTexture.value=I.texture,P.uniforms.decay.value=u,w.material=P,m.setRenderTarget(J),m.render(g,y),F.uniforms.positionTexture.value=H.texture,F.uniforms.velocityTexture.value=J.texture,F.uniforms.pinnedTexture.value=L,F.uniforms.friction.value=1,F.uniforms.spaceSize.value=me,w.material=F,m.setRenderTarget(K),m.render(g,y),m.setRenderTarget(null);let fe=f.get("center");if(fe&&fe.applyToPosition&&(fe.applyToPosition(K.texture,H,o),z.uniforms.sourceTexture.value=H.texture,w.material=z,m.setRenderTarget(K),m.render(g,y),m.setRenderTarget(null)),Y(),V(),!N){let ee=performance.now();ee-q>=k&&(q=ee,qt())}}function mt(){f.forEach(U=>{U.apply(o)});for(let U=0;U<e.length;U++){let H=e[U];H.fx==null?H.x+=H.vx*=u:(H.x=H.fx,H.vx=0),i>1&&(H.fy==null?H.y+=H.vy*=u:(H.y=H.fy,H.vy=0)),i>2&&(H.fz==null?H.z+=H.vz*=u:(H.z=H.fz,H.vz=0))}}let fi=0;function qt(){if(!M||v===0)return;let U=O(),H=new Float32Array(h*h*4);try{m.readRenderTargetPixels(U,0,0,h,h,H),Qn(e,H,i),fi++}catch{}}function gt(U){return U.initialize(e,c,i),M&&U.initGPU&&U.initGPU({renderer:m,scene:g,camera:y,textureSize:h,nodeCount:v}),U}return Ve(e,i,c),r={tick:function(U){return j(U),this},restart:function(){return e.length>0&&!M&&(G(),S()),d?d.restart(ce):d=rt(ce),this},stop:function(){return d?.stop(),this},numDimensions:function(U){return arguments.length===0?i:this},nodes:function(U){return arguments.length===0?e:(e=U,Ve(e,i,c),S(),f.forEach(gt),this)},alpha:function(U){return arguments.length===0?o:(o=+U,this)},alphaMin:function(U){return arguments.length===0?a:(a=+U,this)},alphaDecay:function(U){return arguments.length===0?s:(s=+U,this)},alphaTarget:function(U){return arguments.length===0?l:(l=+U,this)},velocityDecay:function(U){return arguments.length===0?1-u:(u=1-U,P&&(P.uniforms.decay.value=u),this)},randomSource:function(U){return arguments.length===0?c:(c=U,f.forEach(gt),this)},force:function(U,H){if(arguments.length===1)return f.get(U);if(H==null){let K=f.get(U);K?.dispose&&K.dispose(),f.delete(U)}else{let K=gt(H);if(f.set(U,K),M&&K.initGPU&&v>0&&h>0)try{K.initGPU({renderer:m,scene:g,camera:y,textureSize:h,nodeCount:v})}catch{}}return this},find:function(U,H,K,le){H=H??0,K=K??0,le=le??1/0;let J,ve=le*le;for(let me=0;me<e.length;me++){let fe=e[me],ee=U-(fe.x||0),we=H-(fe.y||0),We=K-(fe.z||0),ge=ee*ee+we*we+We*We;ge<ve&&(J=fe,ve=ge)}return J},on:function(U,H){return arguments.length===1?p.on(U):(p.on(U,H),this)},getPositionTexture:function(){if(!M||v===0)return null;let U=O();return!U||!U.texture?null:U.texture},getTextureSize:function(){return h},getSpaceSize:function(){if(!M||v===0)return 10;for(let[,U]of f)if(typeof U.getSpaceSize=="function")return U.getSpaceSize();return qe(v,i)},setSkipCPUReadback:function(U){N=U},getSkipCPUReadback:function(){return N},readBackPositions:function(){qt()},uploadNodePositions:function(U){if(!M||v===0||U.length===0)return;let H=O();if(!H)return;let K=new Float32Array(h*h*4);try{m.readRenderTargetPixels(H,0,0,h,h,K)}catch{return}for(let{index:J,x:ve,y:me,z:fe}of U)if(J>=0&&J<v){let ee=J*4;K[ee]=ve,K[ee+1]=me,K[ee+2]=fe}let le=Oe(K,h);z.uniforms.sourceTexture.value=le,w.material=z,m.setRenderTarget(H),m.render(g,y),m.setRenderTarget(null),le.dispose()},updatePinnedNodes:function(U){if(!L||!M||v===0||U.length===0)return;let H=L.image.data;for(let{index:K,isPinned:le}of U)K>=0&&K<v&&(H[K*4]=le?1:0);L.needsUpdate=!0},debugPositions:function(U=5){if(!M||v===0)return null;let H=O(),K=new Float32Array(h*h*4);try{m.readRenderTargetPixels(H,0,0,h,h,K);let le=[];for(let J=0;J<Math.min(U,v);J++){let ve=K[J*4],me=K[J*4+1],fe=K[J*4+2],ee=K[J*4+3];le.push({x:ve,y:me,z:fe,w:ee})}return le}catch{return null}},dispose:function(){d?.stop(),f.forEach(U=>{U.dispose&&U.dispose()}),f.clear(),b?.dispose(),x?.dispose(),E?.dispose(),A?.dispose(),I?.dispose(),L?.dispose(),B?.dispose(),F?.dispose(),_?.dispose(),z?.dispose(),P?.dispose(),w&&(w.geometry.dispose(),g?.remove(w)),!n&&m&&m.dispose()}},G(),e.length>0&&S(),r}var Qr=`/**
|
|
1546
1546
|
* Center force shader
|
|
1547
1547
|
*
|
|
1548
1548
|
* Implements d3-force's forceCenter behavior:
|
|
@@ -1600,7 +1600,7 @@ void main() {
|
|
|
1600
1600
|
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
1601
1601
|
gl_FragColor = vec4(shift, 1.0);
|
|
1602
1602
|
}
|
|
1603
|
-
`,
|
|
1603
|
+
`,Jr=`/**
|
|
1604
1604
|
* Center force position shader
|
|
1605
1605
|
*
|
|
1606
1606
|
* Implements d3-force's forceCenter behavior correctly:
|
|
@@ -1663,7 +1663,7 @@ void main() {
|
|
|
1663
1663
|
|
|
1664
1664
|
gl_FragColor = vec4(newPos, pos.w);
|
|
1665
1665
|
}
|
|
1666
|
-
`,
|
|
1666
|
+
`,ea=`/**
|
|
1667
1667
|
* Center of mass calculation - vertex shader
|
|
1668
1668
|
*
|
|
1669
1669
|
* Renders each node as a point to a 1x1 texture.
|
|
@@ -1702,7 +1702,7 @@ void main() {
|
|
|
1702
1702
|
// Multiple points at the same location with additive blending will sum up
|
|
1703
1703
|
gl_PointSize = 1.0;
|
|
1704
1704
|
}
|
|
1705
|
-
`,
|
|
1705
|
+
`,ta=`/**
|
|
1706
1706
|
* Center of mass calculation - fragment shader
|
|
1707
1707
|
*
|
|
1708
1708
|
* Outputs position.xyz as RGB and 1.0 as A (for counting).
|
|
@@ -1723,7 +1723,7 @@ void main() {
|
|
|
1723
1723
|
// Output position (xyz) and count (1.0)
|
|
1724
1724
|
gl_FragColor = vec4(pos.xyz, 1.0);
|
|
1725
1725
|
}
|
|
1726
|
-
`;function
|
|
1726
|
+
`;function na(e,t,n){let i=[],r=2,o=e??0,a=t??0,s=n??0,l=1,u=null,c=null,f=null,d=null,p=0,m=0,g=null,y=null,w=null,M=null,h=null,v=null,b=null,x=null,C=null,E=null,A=null,R=null;function I(_,z,P){if(!u||!z||!P||m===0){L(_);return}}function L(_){let z=0,P=0,T=0,k=i.length;for(let S=0;S<k;S++){let D=i[S];z+=D.x||0,P+=D.y||0,T+=D.z||0}let q=(z/k-o)*l,N=(P/k-a)*l,G=(T/k-s)*l;for(let S=0;S<k;S++){let D=i[S];q&&(D.x-=q),r>1&&N&&(D.y-=N),r>2&&G&&(D.z-=G)}}function B(_,z,P){}function F(_,z,P=1){if(!u||!y||!w||!E||!R||!d){console.warn("[GPU ForceCenter] applyToPosition: missing resources");return}g.remove(w);let T=new Q.Mesh(ye(),v);if(g.add(T),u.setRenderTarget(y),u.render(g,d),g.remove(T),T.geometry.dispose(),g.add(w),h.uniforms.positionTexture.value=_,h.uniforms.textureSize.value=p,h.uniforms.nodeCount.value=m,u.setRenderTarget(y),u.render(g,d),Math.random()<.02){let k=new Float32Array(4);u.readRenderTargetPixels(y,0,0,1,1,k);let q=k[0],N=k[1],G=k[2],S=k[3],D=S>0?q/S:0,O=S>0?N/S:0,Y=S>0?G/S:0;console.log(`[GPU ForceCenter] Centermass: sum=(${q.toFixed(2)}, ${N.toFixed(2)}, ${G.toFixed(2)}), count=${S}, avg=(${D.toFixed(4)}, ${O.toFixed(4)}, ${Y.toFixed(4)})`)}R.uniforms.positionTexture.value=_,R.uniforms.centermassTexture.value=y.texture,R.uniforms.centerX.value=o,R.uniforms.centerY.value=a,R.uniforms.centerZ.value=s,R.uniforms.strength.value=l,R.uniforms.alpha.value=P,R.uniforms.textureSize.value=p,R.uniforms.nodeCount.value=m,R.uniforms.nDim.value=r,u.setRenderTarget(z),u.render(E,f),u.setRenderTarget(null)}return I.initialize=function(_,z,P){i=_,r=P},I.initGPU=function(_){u=_.renderer,f=_.camera,p=_.textureSize,m=_.nodeCount,d=new Q.OrthographicCamera(-1,1,1,-1,0,1),g=new Q.Scene,y=Ee(1);let z=Zn(p);M=new Q.BufferGeometry,M.setAttribute("pointIndex",new Q.BufferAttribute(z,2));let P=p*p,T=new Float32Array(P*3);M.setAttribute("position",new Q.BufferAttribute(T,3)),h=new Q.ShaderMaterial({uniforms:{positionTexture:{value:null},textureSize:{value:p},nodeCount:{value:m}},vertexShader:ea,fragmentShader:ta,blending:Q.AdditiveBlending,depthTest:!1,depthWrite:!1}),w=new Q.Points(M,h),g.add(w),console.log(`[GPU ForceCenter] Initialized centermass: ${z.length/2} points, textureSize=${p}, nodeCount=${m}`),console.log(`[GPU ForceCenter] Initialized centermass calculation: ${z.length/2} points, textureSize=${p}, nodeCount=${m}`),v=new Q.ShaderMaterial({uniforms:{},vertexShader:he,fragmentShader:li,blending:Q.NoBlending,depthTest:!1,depthWrite:!1}),b=new Q.Scene,C=new Q.ShaderMaterial({uniforms:{positionTexture:{value:null},centermassTexture:{value:null},centerX:{value:o},centerY:{value:a},centerZ:{value:s},strength:{value:l},textureSize:{value:p},nodeCount:{value:m},nDim:{value:r}},vertexShader:he,fragmentShader:Qr,blending:Q.AdditiveBlending,depthTest:!1,depthWrite:!1}),x=new Q.Mesh(ye(),C),b.add(x),E=new Q.Scene,R=new Q.ShaderMaterial({uniforms:{positionTexture:{value:null},centermassTexture:{value:null},centerX:{value:o},centerY:{value:a},centerZ:{value:s},strength:{value:l},alpha:{value:1},textureSize:{value:p},nodeCount:{value:m},nDim:{value:r}},vertexShader:he,fragmentShader:Jr,blending:Q.NoBlending,depthTest:!1,depthWrite:!1}),A=new Q.Mesh(ye(),R),E.add(A)},I.dispose=function(){y?.dispose(),M?.dispose(),h?.dispose(),v?.dispose(),C?.dispose(),R?.dispose(),x&&x.geometry.dispose(),A&&A.geometry.dispose()},I.apply=I,I.applyToPosition=F,I.x=function(_){return arguments.length===0?o:(o=+_,I)},I.y=function(_){return arguments.length===0?a:(a=+_,I)},I.z=function(_){return arguments.length===0?s:(s=+_,I)},I.strength=function(_){return arguments.length===0?l:(l=+_,I)},I}var ia=`/**
|
|
1727
1727
|
* Quadtree build vertex shader
|
|
1728
1728
|
*
|
|
1729
1729
|
* Accumulates node positions into quadtree cells using point rendering.
|
|
@@ -1784,7 +1784,7 @@ void main() {
|
|
|
1784
1784
|
gl_Position = vec4(levelPosition, 0.0, 1.0);
|
|
1785
1785
|
gl_PointSize = 1.0;
|
|
1786
1786
|
}
|
|
1787
|
-
`,
|
|
1787
|
+
`,ra=`/**
|
|
1788
1788
|
* Quadtree build fragment shader
|
|
1789
1789
|
*
|
|
1790
1790
|
* Simply passes through the accumulated data.
|
|
@@ -1797,7 +1797,7 @@ varying vec4 vData;
|
|
|
1797
1797
|
void main() {
|
|
1798
1798
|
gl_FragColor = vData;
|
|
1799
1799
|
}
|
|
1800
|
-
`;function
|
|
1800
|
+
`;function aa(e,t){e=Math.min(e,t);let n=t-e,i=`
|
|
1801
1801
|
// Match d3-force manyBody.js line 84: skip if beyond distanceMax
|
|
1802
1802
|
if (l >= distanceMax2) {
|
|
1803
1803
|
// Skip this cell (too far)
|
|
@@ -1808,7 +1808,7 @@ void main() {
|
|
|
1808
1808
|
float c = alpha * strength * centermass.b;
|
|
1809
1809
|
addVelocity += calculateAdditionalVelocity(vec2(x, y), l, c, random.rg);
|
|
1810
1810
|
}
|
|
1811
|
-
`;function r(s){if(s>=t)return i;{let l=Math.pow(2,s+1),u=new Array(s+1-n).fill(0).map((d
|
|
1811
|
+
`;function r(s){if(s>=t)return i;{let l=Math.pow(2,s+1),u=new Array(s+1-n).fill(0).map((f,d)=>`pow(2.0, ${s-(d+n)}.0) * i${d+n}`).join("+"),c=new Array(s+1-n).fill(0).map((f,d)=>`pow(2.0, ${s-(d+n)}.0) * j${d+n}`).join("+");return`
|
|
1812
1812
|
for (float ij${s} = 0.0; ij${s} < 4.0; ij${s} += 1.0) {
|
|
1813
1813
|
float i${s} = 0.0;
|
|
1814
1814
|
float j${s} = 0.0;
|
|
@@ -1936,12 +1936,12 @@ void main() {
|
|
|
1936
1936
|
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work correctly
|
|
1937
1937
|
gl_FragColor = vec4(velocity, 0.0, 1.0);
|
|
1938
1938
|
}
|
|
1939
|
-
`}function
|
|
1939
|
+
`}function oa(){let e=[],t=2,n=-30,i=.9,r=1,o=1/0,a=null,s=null,l=0,u=0,c=10,f=0,d=[],p=null,m=null,g=null,y=null,w=null,M=null,h=null;function v(I,L,B){!a||!L||!B||u===0||(C(L),A(I,L,B))}let b=[],x=0;function C(I){if(!a||!m||!g||!s)return;g.uniforms.positionTexture.value=I;let L=a.autoClear,B=a.getClearColor(new $.Color),F=a.getClearAlpha();a.autoClear=!0,a.setClearColor(0,0);for(let _=0;_<f;_++){let z=b[_];g.uniforms.levelTextureSize.value=z.textureSize,g.uniforms.cellSize.value=z.cellSize,a.setRenderTarget(d[_]),a.render(m,s)}a.autoClear=L,a.setClearColor(B,F),a.setRenderTarget(null)}let E=!1;function A(I,L,B){if(!a||!w||!M||!s)return;if(M.uniforms.positionsTexture.value=L,M.uniforms.alpha.value=I,!E){M.uniforms.randomValues.value=p?.texture,M.uniforms.strength.value=n,M.uniforms.theta.value=i,M.uniforms.spaceSize.value=c,M.uniforms.distanceMin.value=r,M.uniforms.distanceMax.value=o===1/0?c*10:o;for(let _=0;_<f;_++)M.uniforms[`level${_}`].value=d[_].texture;E=!0}let F=a.autoClear;a.autoClear=!1,a.setRenderTarget(B),a.render(w,s),a.autoClear=F,a.setRenderTarget(null)}let R=Math.random;return v.initialize=function(I,L,B){e=I,t=B,R=L},v.initGPU=function(I){a=I.renderer,s=I.camera,l=I.textureSize,u=I.nodeCount;let L=qe(u,t),F=Math.max(10,L*2);c=Math.pow(2,Math.ceil(Math.log2(F)));let _=Math.floor(Math.log2(c));f=Math.min(_+4,13);let P=f,T=Math.min(f,14),k=Math.min(f,T),q=f-k,N=new Float32Array(l*l*4);for(let V=0;V<l*l;V++)N[V*4]=R(),N[V*4+1]=R(),N[V*4+2]=0,N[V*4+3]=0;let G=new $.DataTexture(N,l,l,$.RGBAFormat,$.FloatType);G.needsUpdate=!0,p?.dispose(),p=new $.WebGLRenderTarget(l,l,{type:$.FloatType,format:$.RGBAFormat,minFilter:$.NearestFilter,magFilter:$.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});let S=new $.ShaderMaterial({uniforms:{tDiffuse:{value:G}},vertexShader:he,fragmentShader:`
|
|
1940
1940
|
precision highp float;
|
|
1941
1941
|
uniform sampler2D tDiffuse;
|
|
1942
1942
|
varying vec2 vUv;
|
|
1943
1943
|
void main() { gl_FragColor = texture2D(tDiffuse, vUv); }
|
|
1944
|
-
`}),D=new $.Scene,O=new $.Mesh(ye(),
|
|
1944
|
+
`}),D=new $.Scene,O=new $.Mesh(ye(),S);D.add(O),a.setRenderTarget(p),a.render(D,s),a.setRenderTarget(null),S.dispose(),O.geometry.dispose(),G.dispose(),d.forEach(V=>V.dispose()),d=[],b=[];for(let V=0;V<f;V++){let ce=Math.pow(2,V+1),j=new $.WebGLRenderTarget(ce,ce,{type:$.FloatType,format:$.RGBAFormat,minFilter:$.NearestFilter,magFilter:$.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});d.push(j),b.push({textureSize:ce,cellSize:c/ce})}let Y;if(u!==x){let V=new Float32Array(u*2),ce=new Float32Array(u*3);for(let j=0;j<u;j++)V[j*2]=j%l,V[j*2+1]=Math.floor(j/l),ce[j*3]=0,ce[j*3+1]=0,ce[j*3+2]=0;Y=new $.BufferGeometry,Y.setAttribute("position",new $.BufferAttribute(ce,3)),Y.setAttribute("pointIndex",new $.BufferAttribute(V,2)),x=u}else Y=y.geometry;if(g?.dispose(),g=new $.ShaderMaterial({uniforms:{positionTexture:{value:null},pointsTextureSize:{value:l},levelTextureSize:{value:2},cellSize:{value:c/2},spaceSize:{value:c}},vertexShader:ia,fragmentShader:ra,blending:$.AdditiveBlending,depthTest:!1,depthWrite:!1}),m||(m=new $.Scene),y){if(y.material=g,u!==x){let V=y.geometry;y.geometry=Y,V.dispose()}}else y=new $.Points(Y,g),m.add(y);M?.dispose(),E=!1;let X={positionsTexture:{value:null},randomValues:{value:null},spaceSize:{value:c},strength:{value:n},theta:{value:i},alpha:{value:1},distanceMin:{value:r},distanceMax:{value:o===1/0?c*10:o}};for(let V=0;V<f;V++)X[`level${V}`]={value:null};let W=aa(k,f);M=new $.ShaderMaterial({uniforms:X,vertexShader:he,fragmentShader:W,blending:$.AdditiveBlending,depthTest:!1,depthWrite:!1}),w||(w=new $.Scene),h?h.material=M:(h=new $.Mesh(ye(),M),w.add(h))},v.dispose=function(){d.forEach(I=>I.dispose()),d=[],b=[],E=!1,p?.dispose(),p=null,g?.dispose(),M?.dispose(),y?.geometry.dispose(),h?.geometry.dispose()},v.apply=v,v.strength=function(I){return arguments.length===0?n:(n=+I,M&&(M.uniforms.strength.value=n),v)},v.theta=function(I){return arguments.length===0?i:(i=+I,E=!1,v)},v.distanceMin=function(I){return arguments.length===0?r:(r=+I,E=!1,v)},v.distanceMax=function(I){return arguments.length===0?o:(o=+I,E=!1,v)},v}var sa=`
|
|
1945
1945
|
precision highp float;
|
|
1946
1946
|
|
|
1947
1947
|
uniform sampler2D positionTexture;
|
|
@@ -1990,20 +1990,20 @@ void main() {
|
|
|
1990
1990
|
gl_Position = vec4(levelPosition, 0.0, 1.0);
|
|
1991
1991
|
gl_PointSize = 1.0;
|
|
1992
1992
|
}
|
|
1993
|
-
`,
|
|
1993
|
+
`,la=`
|
|
1994
1994
|
precision highp float;
|
|
1995
1995
|
varying vec4 vData;
|
|
1996
1996
|
void main() {
|
|
1997
1997
|
gl_FragColor = vData;
|
|
1998
1998
|
}
|
|
1999
|
-
`;function
|
|
1999
|
+
`;function ua(e,t){e=Math.min(e,t);let n=t-e;function i(s){let l=t-1-Math.min(s,t-1);return`
|
|
2000
2000
|
if (l >= distanceMax2) {
|
|
2001
2001
|
// Skip this cell (too far)
|
|
2002
2002
|
} else {
|
|
2003
2003
|
float c = alpha * strength * centermass.w * ${Math.pow(Math.sqrt(4/8),l).toFixed(6)};
|
|
2004
2004
|
addVelocity += calculateAdditionalVelocity(vec3(dx, dy, dz), l, c, random.rgb);
|
|
2005
2005
|
}
|
|
2006
|
-
`}function r(s){if(s>=t)return i(t-1);{let l=Math.pow(2,s+1),u=new Array(s+1-n).fill(0).map((
|
|
2006
|
+
`}function r(s){if(s>=t)return i(t-1);{let l=Math.pow(2,s+1),u=new Array(s+1-n).fill(0).map((d,p)=>`pow(2.0, ${s-(p+n)}.0) * i${p+n}`).join("+"),c=new Array(s+1-n).fill(0).map((d,p)=>`pow(2.0, ${s-(p+n)}.0) * j${p+n}`).join("+"),f=new Array(s+1-n).fill(0).map((d,p)=>`pow(2.0, ${s-(p+n)}.0) * k${p+n}`).join("+");return`
|
|
2007
2007
|
for (float ijk${s} = 0.0; ijk${s} < 8.0; ijk${s} += 1.0) {
|
|
2008
2008
|
float i${s} = mod(ijk${s}, 2.0);
|
|
2009
2009
|
float j${s} = mod(floor(ijk${s} / 2.0), 2.0);
|
|
@@ -2011,7 +2011,7 @@ void main() {
|
|
|
2011
2011
|
|
|
2012
2012
|
float cellI = pow(2.0, ${e}.0) * outerI / width${s+1} + ${u};
|
|
2013
2013
|
float cellJ = pow(2.0, ${e}.0) * outerJ / width${s+1} + ${c};
|
|
2014
|
-
float cellK = pow(2.0, ${e}.0) * outerK / width${s+1} + ${
|
|
2014
|
+
float cellK = pow(2.0, ${e}.0) * outerK / width${s+1} + ${f};
|
|
2015
2015
|
|
|
2016
2016
|
// Sample from flattened 2D texture
|
|
2017
2017
|
// 3D (cellI, cellJ, cellK) \u2192 2D (cellI + cellK * gridSize, cellJ)
|
|
@@ -2130,12 +2130,12 @@ void main() {
|
|
|
2130
2130
|
// Output 3D velocity (xyz) with alpha = 1.0 for blending
|
|
2131
2131
|
gl_FragColor = vec4(velocity, 1.0);
|
|
2132
2132
|
}
|
|
2133
|
-
`}function
|
|
2133
|
+
`}function ca(){let e=[],t=2,n=-30,i=.5,r=1,o=1/0,a=null,s=null,l=null,u=0,c=0,f=10,d=0,p=[],m=null,g=null,y=null,w=null,M=null,h=null,v=null;function b(L,B,F){!s||!B||!F||c===0||(E(B),R(L,B,F))}let x=[],C=0;function E(L){if(!s||!g||!y||!l)return;y.uniforms.positionTexture.value=L;let B=s.autoClear,F=s.getClearColor(new Z.Color),_=s.getClearAlpha();s.autoClear=!0,s.setClearColor(0,0);for(let z=0;z<d;z++){let P=x[z];y.uniforms.levelSize.value=P.levelSize,y.uniforms.levelTextureWidth.value=P.textureWidth,y.uniforms.levelTextureHeight.value=P.textureHeight,y.uniforms.cellSize.value=P.cellSize,s.setRenderTarget(p[z]),s.render(g,l)}s.autoClear=B,s.setClearColor(F,_),s.setRenderTarget(null)}let A=!1;function R(L,B,F){if(!s||!M||!h||!l)return;if(h.uniforms.positionsTexture.value=B,h.uniforms.alpha.value=L,!A){h.uniforms.randomValues.value=m?.texture,h.uniforms.strength.value=n,h.uniforms.theta.value=i,h.uniforms.spaceSize.value=f,h.uniforms.distanceMin.value=r,h.uniforms.distanceMax.value=o===1/0?f*10:o;for(let z=0;z<d;z++)h.uniforms[`level${z}`].value=p[z].texture;A=!0}let _=s.autoClear;s.autoClear=!1,s.setRenderTarget(F),s.render(M,l),s.autoClear=_,s.setRenderTarget(null)}let I=Math.random;return b.initialize=function(L,B,F){e=L,t=F,I=B},b.initGPU=function(L){s=L.renderer,l=L.camera,u=L.textureSize,c=L.nodeCount;let B=qe(c,t),F=Math.min(20,6+Math.log10(Math.max(c,2))),_=Math.max(40,B*F);_>8192&&console.warn(`[ManyBody Octree 3D] paddedSpaceSize=${_.toFixed(0)} exceeds cap 8192; clamping. N=${c} may have boundary spike. Consider Option B adaptive resize.`),f=Math.min(8192,Math.pow(2,Math.ceil(Math.log2(_))));let z=s.getContext(),P=z.getParameter(z.MAX_TEXTURE_SIZE);console.log(`[ManyBody Octree 3D] GPU MAX_TEXTURE_SIZE = ${P}`);let T=Math.floor(Math.log2(P)/2),k=Math.min(Math.floor(Math.log2(f)),T,8);d=a!==null?Math.min(a,k):k,console.log(`[ManyBody Octree 3D] nodeCount=${c}, spaceSize=${f}, maxGPUTexture=${P}`),console.log(`[ManyBody Octree 3D] calculatedLevels=${k}, initialOctreeLevels=${d}`),console.log(`[ManyBody Octree 3D] theta=${i}, strength=${n}`);let q=new Float32Array(u*u*4);for(let j=0;j<u*u;j++)q[j*4]=I(),q[j*4+1]=I(),q[j*4+2]=I(),q[j*4+3]=0;let N=new Z.DataTexture(q,u,u,Z.RGBAFormat,Z.FloatType);N.needsUpdate=!0,m?.dispose(),m=new Z.WebGLRenderTarget(u,u,{type:Z.FloatType,format:Z.RGBAFormat,minFilter:Z.NearestFilter,magFilter:Z.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});let G=new Z.ShaderMaterial({uniforms:{tDiffuse:{value:N}},vertexShader:he,fragmentShader:`
|
|
2134
2134
|
precision highp float;
|
|
2135
2135
|
uniform sampler2D tDiffuse;
|
|
2136
2136
|
varying vec2 vUv;
|
|
2137
2137
|
void main() { gl_FragColor = texture2D(tDiffuse, vUv); }
|
|
2138
|
-
`}),
|
|
2138
|
+
`}),S=new Z.Scene,D=new Z.Mesh(ye(),G);S.add(D),s.setRenderTarget(m),s.render(S,l),s.setRenderTarget(null),G.dispose(),D.geometry.dispose(),N.dispose(),p.forEach(j=>j.dispose()),p=[],x=[];for(let j=0;j<d;j++){let de=Math.pow(2,j+1),ie=de*de,Be=de;if(ie>P||Be>P){console.error(`[ManyBody Octree 3D] Level ${j} texture ${ie}\xD7${Be} exceeds GPU limit ${P}! Skipping remaining levels.`),d=j;break}let mt=new Z.WebGLRenderTarget(ie,Be,{type:Z.FloatType,format:Z.RGBAFormat,minFilter:Z.NearestFilter,magFilter:Z.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});p.push(mt),x.push({levelSize:de,textureWidth:ie,textureHeight:Be,cellSize:f/de}),console.log(`[ManyBody Octree 3D] Level ${j}: grid=${de}\xB3, texture=${ie}\xD7${Be}`)}let O=Math.min(d,8),Y=Math.min(d,O),X=d-Y;console.log(`[ManyBody Octree 3D] Final: octreeLevels=${d}, shaderStartLevel=${Y}, delta=${X}`);let W;if(c!==C){let j=new Float32Array(c*2),de=new Float32Array(c*3);for(let ie=0;ie<c;ie++)j[ie*2]=ie%u,j[ie*2+1]=Math.floor(ie/u),de[ie*3]=0,de[ie*3+1]=0,de[ie*3+2]=0;W=new Z.BufferGeometry,W.setAttribute("position",new Z.BufferAttribute(de,3)),W.setAttribute("pointIndex",new Z.BufferAttribute(j,2)),C=c}else W=w.geometry;if(y?.dispose(),y=new Z.ShaderMaterial({uniforms:{positionTexture:{value:null},pointsTextureSize:{value:u},levelSize:{value:2},levelTextureWidth:{value:4},levelTextureHeight:{value:2},cellSize:{value:f/2},spaceSize:{value:f}},vertexShader:sa,fragmentShader:la,blending:Z.AdditiveBlending,depthTest:!1,depthWrite:!1}),g||(g=new Z.Scene),w){if(w.material=y,c!==C){let j=w.geometry;w.geometry=W,j.dispose()}}else w=new Z.Points(W,y),g.add(w);h?.dispose(),A=!1;let V={positionsTexture:{value:null},randomValues:{value:null},spaceSize:{value:f},strength:{value:n},theta:{value:i},alpha:{value:1},distanceMin:{value:r},distanceMax:{value:o===1/0?f*10:o}};for(let j=0;j<d;j++)V[`level${j}`]={value:null};let ce=ua(Y,d);h=new Z.ShaderMaterial({uniforms:V,vertexShader:he,fragmentShader:ce,blending:Z.AdditiveBlending,depthTest:!1,depthWrite:!1}),M||(M=new Z.Scene),v?v.material=h:(v=new Z.Mesh(ye(),h),M.add(v))},b.dispose=function(){p.forEach(L=>L.dispose()),p=[],x=[],A=!1,m?.dispose(),m=null,y?.dispose(),h?.dispose(),w?.geometry.dispose(),v?.geometry.dispose()},b.apply=b,b.strength=function(L){return arguments.length===0?n:(n=+L,h&&(h.uniforms.strength.value=n),b)},b.theta=function(L){return arguments.length===0?i:(i=+L,A=!1,b)},b.distanceMin=function(L){return arguments.length===0?r:(r=+L,A=!1,b)},b.distanceMax=function(L){return arguments.length===0?o:(o=+L,A=!1,b)},b.maxLevels=function(L){return arguments.length===0?a??null:(a=L>0?Math.min(L,8):null,A=!1,b)},b.getSpaceSize=function(){return typeof f=="number"&&f>0?f:10},b}var da=`/**
|
|
2139
2139
|
* Link force vertex shader
|
|
2140
2140
|
*
|
|
2141
2141
|
* Each point represents one endpoint of a link.
|
|
@@ -2167,7 +2167,7 @@ void main() {
|
|
|
2167
2167
|
gl_Position = vec4(pos, 0.0, 1.0);
|
|
2168
2168
|
gl_PointSize = 1.0;
|
|
2169
2169
|
}
|
|
2170
|
-
|
|
2170
|
+
`,fa=`/**
|
|
2171
2171
|
* Link force fragment shader
|
|
2172
2172
|
*
|
|
2173
2173
|
* Implements d3-force's forceLink spring behavior:
|
|
@@ -2267,7 +2267,7 @@ void main() {
|
|
|
2267
2267
|
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
2268
2268
|
gl_FragColor = vec4(velocity, 1.0);
|
|
2269
2269
|
}
|
|
2270
|
-
`;function
|
|
2270
|
+
`;function pa(e){let t=[],n=e||[],i=2,r=Math.random,o=B=>B.index,a=C,s=te(30),l=1,u=[],c=[],f=[],d=[],p=null,m=null,g=null,y=0,w=0,M=null,h=null,v=null,b=null,x=0;function C(B){let F=typeof B.source=="object"?B.source.index:0,_=typeof B.target=="object"?B.target.index:0;return 1/Math.min(u[F]||1,u[_]||1)}function E(){if(!t||t.length===0)return;let B=t.length,F=n.length,_=new Map;for(let T=0;T<B;T++)_.set(o(t[T],T,t),t[T]);u=new Array(B).fill(0);for(let T=0;T<F;T++){let k=n[T];if(k.index=T,typeof k.source!="object"){let q=_.get(k.source);if(!q)throw new Error(`Link source not found: ${k.source}`);k.source=q}if(typeof k.target!="object"){let q=_.get(k.target);if(!q)throw new Error(`Link target not found: ${k.target}`);k.target=q}u[k.source.index]++,u[k.target.index]++}c=new Array(F);for(let T=0;T<F;T++){let k=n[T],q=k.source.index,N=k.target.index;c[T]=u[q]/(u[q]+u[N])}f=new Array(F),d=new Array(F);let z=typeof a=="function"?a:()=>a,P=typeof s=="function"?s:()=>s;for(let T=0;T<F;T++)f[T]=+z(n[T],T,n),d[T]=+P(n[T],T,n);A()}function A(){if(!b||n.length===0)return;let B=b.image.data;for(let F=0;F<n.length;F++){let _=n[F],z=_.source.index,P=_.target.index,T=F*4;B[T]=z,B[T+1]=P,B[T+2]=d[F],B[T+3]=f[F]}b.needsUpdate=!0}function R(B,F,_){if(n.length!==0){if(!p||!F||!_||w===0){I(B);return}L(B,F,_)}}function I(B){for(let F=0;F<l;F++)for(let _=0;_<n.length;_++){let z=n[_],P=z.source,T=z.target,k=(T.x||0)+(T.vx||0)-(P.x||0)-(P.vx||0)||dt(r),q=i>1?(T.y||0)+(T.vy||0)-(P.y||0)-(P.vy||0)||dt(r):0,N=i>2?(T.z||0)+(T.vz||0)-(P.z||0)-(P.vz||0)||dt(r):0,G=Math.sqrt(k*k+q*q+N*N);G=(G-d[_])/G*B*f[_],k*=G,q*=G,N*=G;let S=c[_];T.vx-=k*S,i>1&&(T.vy-=q*S),i>2&&(T.vz-=N*S),P.vx+=k*(1-S),i>1&&(P.vy+=q*(1-S)),i>2&&(P.vz+=N*(1-S))}}function L(B,F,_){if(!M||!v)return;v.uniforms.positionTexture.value=F,v.uniforms.linkTexture.value=b,v.uniforms.linkTextureSize.value=x,v.uniforms.nodeTextureSize.value=y,v.uniforms.nodeCount.value=w,v.uniforms.alpha.value=B,v.uniforms.nDim.value=i;let z=p.autoClear;p.autoClear=!1;for(let P=0;P<l;P++)p.setRenderTarget(_),m&&p.render(m,g);p.autoClear=z,p.setRenderTarget(null)}return R.initialize=function(B,F,_){t=B,r=F,i=_,E()},R.initGPU=function(B){if(p=B.renderer,g=B.camera,y=B.textureSize,w=B.nodeCount,n.length===0)return;x=At(n.length);let F=new Float32Array(x*x*4);F.fill(-1);for(let T=0;T<n.length;T++){let k=n[T],q=k.source.index,N=k.target.index,G=T*4;F[G]=q,F[G+1]=N,F[G+2]=d[T],F[G+3]=f[T]}b?.dispose(),b=new ne.DataTexture(F,x,x,ne.RGBAFormat,ne.FloatType),b.needsUpdate=!0;let _=n.length*2,z=new Float32Array(_*2);for(let T=0;T<n.length;T++){let k=n[T],q=k.source.index,N=k.target.index;z[T*4]=T*2,z[T*4+1]=q,z[T*4+2]=T*2+1,z[T*4+3]=N}h?.dispose(),h=new ne.BufferGeometry,h.setAttribute("linkEndpoint",new ne.BufferAttribute(z,2));let P=new Float32Array(z.length/2*3);h.setAttribute("position",new ne.BufferAttribute(P,3)),v?.dispose(),v=new ne.ShaderMaterial({uniforms:{positionTexture:{value:null},linkTexture:{value:b},linkTextureSize:{value:x},nodeTextureSize:{value:y},nodeCount:{value:w},alpha:{value:1},nDim:{value:i}},vertexShader:da,fragmentShader:fa,blending:ne.AdditiveBlending,depthTest:!1,depthWrite:!1}),M&&m&&m.remove(M),m=new ne.Scene,M=new ne.Points(h,v),m.add(M)},R.dispose=function(){b?.dispose(),h?.dispose(),v?.dispose(),M&&m?.remove(M)},R.apply=R,R.links=function(B){return arguments.length===0?n:(n=B,E(),R)},R.id=function(B){return arguments.length===0?o:(o=B,R)},R.iterations=function(B){return arguments.length===0?l:(l=+B,R)},R.strength=function(B){return arguments.length===0?a:(a=typeof B=="function"?B:te(+B),E(),A(),R)},R.distance=function(B){return arguments.length===0?s:(s=typeof B=="function"?B:te(+B),E(),A(),R)},R}var Lt=`/**
|
|
2271
2271
|
* Position force shader (forceX/Y/Z)
|
|
2272
2272
|
*
|
|
2273
2273
|
* Implements d3-force's forceX/forceY/forceZ:
|
|
@@ -2324,5 +2324,5 @@ void main() {
|
|
|
2324
2324
|
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
2325
2325
|
gl_FragColor = vec4(velocity, 1.0);
|
|
2326
2326
|
}
|
|
2327
|
-
`;function jr(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,d=null,f=null,p=null;function g(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&m()}function m(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!f||!p){M(h);return}S(h,v,b)}function M(h){for(let v=0;v<t.length;v++){let b=t[v];b.vx+=(o[v]-(b.x||0))*r[v]*h}}function S(h,v,b){f.uniforms.positionTexture.value=v,f.uniforms.targetTexture.value=p,f.uniforms.alpha.value=h,f.uniforms.textureSize.value=u,f.uniforms.nodeCount.value=c,f.uniforms.axis.value=0;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,g()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&g();let v=u*u,b=new Float32Array(v*4),x=0,E=0;for(let F=0;F<t.length;F++){let R=F*4;b[R]=o[F]??0,b[R+1]=r[F]??0,b[R+2]=0,b[R+3]=0,F<10&&(x+=r[F]??0,E+=o[F]??0)}p?.dispose(),p=new ae.DataTexture(b,u,u,ae.RGBAFormat,ae.FloatType),p.minFilter=ae.NearestFilter,p.magFilter=ae.NearestFilter,p.needsUpdate=!0,s=new ae.Scene,f=new ae.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:0}},vertexShader:he,fragmentShader:Ft,blending:ae.AdditiveBlending,depthTest:!1,depthWrite:!1}),d=new ae.Mesh(ye(),f),s.add(d)},y.dispose=function(){p?.dispose(),f?.dispose(),d&&(d.geometry.dispose(),s?.remove(d))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),g(),y)},y.x=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),g(),y)},y}function Vr(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,d=null,f=null,p=null;function g(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&m()}function m(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!f||!p){M(h);return}S(h,v,b)}function M(h){for(let v=0;v<t.length;v++){let b=t[v];b.vy+=(o[v]-(b.y||0))*r[v]*h}}function S(h,v,b){f.uniforms.positionTexture.value=v,f.uniforms.targetTexture.value=p,f.uniforms.alpha.value=h,f.uniforms.textureSize.value=u,f.uniforms.nodeCount.value=c,f.uniforms.axis.value=1;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,g()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&g();let v=u*u,b=new Float32Array(v*4),x=0,E=0;for(let F=0;F<t.length;F++){let R=F*4,A=o[F]??0,I=r[F]??0;b[R]=A,b[R+1]=I,b[R+2]=0,b[R+3]=0,F<10&&(x+=A,E+=I)}t.length>0,p?.dispose(),p=new oe.DataTexture(b,u,u,oe.RGBAFormat,oe.FloatType),p.minFilter=oe.NearestFilter,p.magFilter=oe.NearestFilter,p.needsUpdate=!0,s=new oe.Scene,f=new oe.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:1}},vertexShader:he,fragmentShader:Ft,blending:oe.AdditiveBlending,depthTest:!1,depthWrite:!1}),d=new oe.Mesh(ye(),f),s.add(d)},y.dispose=function(){p?.dispose(),f?.dispose(),d&&(d.geometry.dispose(),s?.remove(d))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),g(),y)},y.y=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),g(),y)},y}function Wr(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,d=null,f=null,p=null;function g(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&m()}function m(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!f||!p){M(h);return}S(h,v,b)}function M(h){for(let v=0;v<t.length;v++){let b=t[v];b.vz+=(o[v]-(b.z||0))*r[v]*h}}function S(h,v,b){f.uniforms.positionTexture.value=v,f.uniforms.targetTexture.value=p,f.uniforms.alpha.value=h,f.uniforms.textureSize.value=u,f.uniforms.nodeCount.value=c,f.uniforms.axis.value=2;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,g()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&g();let v=u*u,b=new Float32Array(v*4);for(let x=0;x<t.length;x++){let E=x*4;b[E]=o[x]??0,b[E+1]=r[x]??0,b[E+2]=0,b[E+3]=0}p?.dispose(),p=new se.DataTexture(b,u,u,se.RGBAFormat,se.FloatType),p.minFilter=se.NearestFilter,p.magFilter=se.NearestFilter,p.needsUpdate=!0,s=new se.Scene,f=new se.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:2}},vertexShader:he,fragmentShader:Ft,blending:se.AdditiveBlending,depthTest:!1,depthWrite:!1}),d=new se.Mesh(ye(),f),s.add(d)},y.dispose=function(){p?.dispose(),f?.dispose(),d&&(d.geometry.dispose(),s?.remove(d))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),g(),y)},y.z=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),g(),y)},y}var lt={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},It=class{constructor(e,t){if(this.simulation=null,this.getOptions=null,this._enable=!0,this._isFinish=!1,this.nodeIdToIndex=new Map,this.lastUpdateTime=0,this.updateIntervalMs=1e3/24,this.skipCPUPositionUpdate=!1,this._dimTransition=null,this._gpuZZeroed=!1,this.graph=e,t)this.renderer=t;else{let n=document.createElement("canvas");n.style.display="none",this.renderer=new jn.WebGLRenderer({canvas:n,alpha:!0,antialias:!1}),this.renderer.setSize(256,256)}this.params={...lt}}config(e){if(this.getOptions=e,e){let t=e();t&&this.applyConfig(t)}return this}configure(e){return this.config(e)}applyConfig(e){e.friction!==void 0&&e.velocityDecay===void 0&&(e.velocityDecay=e.friction),Object.assign(this.params,e)}calculateForces(){let e=this.params.heightCompress??1,t=this.params.gravity??.1,n=this.params.dimensions??3,i,r,o,a;return n===2?(r=t*1.5,i=0,o=.02,a=.8):(i=t*Math.sqrt(e),r=t/Math.sqrt(e),i=i>10?10:i,o=lt.alphaDecay??.1,a=lt.alpha??.6),{forcexy:r,forcez:i,alphaDecay:o,alpha:a}}startLayout(e=0,t=0,n=!1){let i=this.params.dimensions;if(this.getOptions){let w=this.getOptions();w&&this.applyConfig(w)}this.params.dimensions=i,this._gpuZZeroed=!1;let r=this.graph.layoutNodes||[],o=this.graph.layoutEdges||[];if(r.length===0)return;this.nodeIdToIndex.clear(),r.forEach((w,z)=>{this.nodeIdToIndex.set(w.id,z)});let a=this.params.dimensions??3;this.params.dimensions=a;let s=r.some(w=>Math.abs(w.position.z)>1e-6),l=Math.cbrt(r.length)*2,u=a>2&&!s&&!n,c=r.map((w,z)=>{let P=w.position.x,T=w.position.y,C=a<=2?0:w.position.z;if(u&&!w.pinned){let q=Math.random(),N=Math.random(),G=Math.random(),_=2*Math.PI*q,D=Math.acos(2*N-1),O=Math.cbrt(G)*l;P=O*Math.sin(D)*Math.cos(_),T=O*Math.sin(D)*Math.sin(_),C=O*Math.cos(D)}return{...w,index:z,x:P,y:T,z:C,vx:0,vy:0,vz:0,fx:w.pinned?w.position.x:null,fy:w.pinned?w.position.y:null,fz:w.pinned?w.position.z:null}}),d=o.filter(w=>{let z=this.nodeIdToIndex.get(w.sourceId),P=this.nodeIdToIndex.get(w.targetId);return z!==void 0&&P!==void 0}).map(w=>({source:w.sourceId,target:w.targetId}));this.simulation&&(this.simulation.stop(),this.simulation.dispose()),this.simulation=Er(c,a,this.renderer);let{forcexy:f,forcez:p,alphaDecay:g,alpha:m}=this.calculateForces(),y=this.params.charge??-.01,M=r.length,S=this.params.gravityX??1,h=this.params.gravityY??1,v=this.params.gravityZ??1,b=this.params.linkDistance??.5,x=this.params.linkStrength??1,E=f*this.params.gravityX,F=f*this.params.gravityY,R=p*this.params.gravityZ,A=jr(0).strength(E),I=Vr(0).strength(F);if(this.simulation.force("x",A),this.simulation.force("y",I),a>2){let w=Wr(0).strength(R);this.simulation.force("z",w)}if(this.simulation.force("center",Rr(0,0,0).strength(1)),a>2){let w=Xr();w.strength(y);let z=this.params.octreeTheta??.8,P=r.length,T=Math.max(.2,Math.min(1,1.2-.1*Math.log10(Math.max(P,1)))),C=z*T;w.theta(C);let q=this.params.octreeLevels;q!==void 0&&w.maxLevels(q),this.simulation.force("charge",w)}else{let w=Nr();w.strength(y);let z=this.params.quadtreeTheta??.9,P=Math.max(.5,Math.min(1,500/Math.sqrt(r.length))),T=z*P;w.theta(T),this.simulation.force("charge",w)}if(d.length>0){let w=Zr(d);w.distance(b),w.strength(x),w.id(z=>z.id),this.simulation.force("link",w)}(this.params.collision??.15)>0;let B=this.params.velocityDecay??lt.velocityDecay;this.simulation.alpha(m).alphaMin(.001).alphaDecay(g).velocityDecay(B),this.simulation.on("tick",()=>{this.onTick()}),this.simulation.on("end",()=>{this._isFinish=!0,this.graph.renderNeedsUpdate=!1}),this._isFinish=!1,this._enable=!0,this.graph.renderNeedsUpdate=!0,this.skipCPUPositionUpdate&&this.simulation.setSkipCPUReadback(!0),this.simulation.restart()}onTick(){if(!this._enable||!this.simulation)return;if(this.skipCPUPositionUpdate){(this.params.dimensions??3)<=2&&this.ensureGPUZeroZ(),this.graph.renderNeedsUpdate=!0;return}let e=performance.now();if(e-this.lastUpdateTime<this.updateIntervalMs)return;this.lastUpdateTime=e;let t=this.simulation.nodes(),n=this.params.dimensions??3;t.forEach(i=>{let r=this.nodeIdToIndex.get(i.id);if(r!==void 0&&r<this.graph.layoutNodes.length){let o=this.graph.layoutNodes[r];o&&!o.pinned&&i.fx==null&&(o.position.x=i.x??0,o.position.y=i.y??0,n>2?o.position.z=i.z??0:o.position.z=0,o.isPositionDirty=!0)}}),this.graph.renderNeedsUpdate=!0}ensureGPUZeroZ(){if(this._gpuZZeroed||!this.simulation)return;this._gpuZZeroed=!0,this.simulation.readBackPositions();let e=this.simulation.nodes(),t=[];e.forEach((i,r)=>{Math.abs(i.z??0)>1e-6&&t.push({index:r,x:i.x??0,y:i.y??0,z:0})}),t.length>0&&this.simulation.uploadNodePositions(t);let n=this.graph.layoutNodes;for(let i=0;i<n.length;i++)n[i].position.z=0}restartLayout(){if(!this.simulation||!this._enable)return;if(this.getOptions){let M=this.getOptions();M&&this.applyConfig(M)}let e=this.params.dimensions??3,{forcexy:t,forcez:n,alphaDecay:i,alpha:r}=this.calculateForces(),o=this.params.charge??-.01,a=this.params.linkDistance??.5,s=this.params.linkStrength??1,l=t*(this.params.gravityX??1),u=t*(this.params.gravityY??1),c=n*(this.params.gravityZ??1),d=this.simulation.force("x"),f=this.simulation.force("y"),p=this.simulation.force("z"),g=this.simulation.force("charge"),m=this.simulation.force("link");d&&d.strength(l),f&&f.strength(u),p&&e>2&&p.strength(c),g&&g.strength(o),m&&(m.distance(a),m.strength(s));let y=this.params.velocityDecay??.3;this.simulation.alpha(r).alphaDecay(i).velocityDecay(y).restart(),this._isFinish=!1,this.graph.renderNeedsUpdate=!0}stopLayout(){this.simulation&&this.simulation.stop(),this._isFinish=!0,this.graph.renderNeedsUpdate=!1}updateLayoutOption(e,t){if(e==="friction"?this.params.velocityDecay=t:this.params[e]=t,!this.simulation||!this._enable)return;let n=this.simulation.force("charge"),i=this.simulation.force("link"),r=this.simulation.force("x"),o=this.simulation.force("y"),a=this.simulation.force("z");switch(e){case"charge":n&&(n.strength(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"linkDistance":i&&(i.distance(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"linkStrength":i&&(i.strength(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"gravity":case"gravityX":case"gravityY":case"gravityZ":case"heightCompress":let{forcexy:s,forcez:l}=this.calculateForces(),u=s*(this.params.gravityX??1),c=s*(this.params.gravityY??1),d=l*(this.params.gravityZ??1);r&&r.strength(u),o&&o.strength(c),a&&a.strength(d),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart();break;case"velocityDecay":case"friction":this.simulation.velocityDecay(this.params.velocityDecay??.3);break;case"alpha":case"alphaDecay":this.restartLayout();break;default:this.restartLayout();break}this.graph.renderNeedsUpdate=!0}pinNodes(e){if(!this.simulation)return;let t=this.simulation.nodes(),n=[];e.forEach(r=>{let o=this.nodeIdToIndex.get(r.id);if(o!==void 0){let a=this.graph.layoutNodes[o];a&&(a.pinned=!0);let s=t[o];s&&(s.fx=r.position.x,s.fy=r.position.y,s.fz=r.position.z,n.push({index:o,x:r.position.x,y:r.position.y,z:r.position.z}))}}),n.length>0&&this.simulation.uploadNodePositions(n);let i=n.map(r=>({index:r.index,isPinned:!0}));this.simulation.updatePinnedNodes(i),this._enable&&this.simulation.alpha()<.1&&this.simulation.alpha(.3).restart(),this.graph.renderNeedsUpdate=!0}unpinNodes(e){if(!this.simulation)return;let t=this.simulation.nodes(),n=[];for(let i of e){let r=this.nodeIdToIndex.get(i);if(r===void 0)continue;let o=this.graph.layoutNodes[r];o&&(o.pinned=!1);let a=t[r];a&&(a.fx=null,a.fy=null,a.fz=null),n.push({index:r,isPinned:!1})}n.length>0&&this.simulation.updatePinnedNodes(n),this._enable&&this.simulation.alpha()<.05&&this.simulation.alpha(.15).restart(),this.graph.renderNeedsUpdate=!0}set enable(e){this._enable=e,!e&&this.simulation&&this.simulation.stop(),this._isFinish=!e,this.graph.renderNeedsUpdate=e}get enable(){return this._enable}get isFinish(){return this._isFinish}setExpectedNodeCount(e){}clearExpectedNodeCount(){}updateGraph(e,t,n=!1){this.startLayout()}destroy(){this.cancelDimensionTransition(),this.simulation&&(this.simulation.stop(),this.simulation.dispose(),this.simulation=null)}transitionDimensions(e,t=600){(this.params.dimensions??3)!==e&&(e===2?this.transition3Dto2D(t):this.transition2Dto3D())}transition3Dto2D(e){this.readBackPositions(),this.params.dimensions=2,this.startLayout(0,0,!0)}transition2Dto3D(){this.readBackPositions(),this.params.dimensions=3,this.startLayout()}cancelDimensionTransition(){this._dimTransition=null}getDimensions(){return this.params.dimensions??3}debugNodePositions(){let e=this.simulation?this.simulation.nodes():[];if(this.simulation&&e.length>0)for(let n=0;n<Math.min(3,e.length);n++){let i=e[n]}let t=this.graph.layoutNodes||[];if(t.length>0){for(let n=0;n<Math.min(3,t.length);n++){let i=t[n]}if(this.simulation&&e.length>0)for(let n=0;n<Math.min(3,Math.min(e.length,t.length));n++){let i=e[n],r=t.find(o=>o.id===i.id);if(r){let o=Math.abs((i.x??0)-r.position.x)<.001&&Math.abs((i.y??0)-r.position.y)<.001&&Math.abs((i.z??0)-r.position.z)<.001}}}}getPositionTexture(){return this.simulation?this.simulation.getPositionTexture():null}getTextureSize(){return this.simulation?this.simulation.getTextureSize():0}getSpaceSize(){return this.simulation?this.simulation.getSpaceSize():10}debugGPUPositions(e=5){return this.simulation?this.simulation.debugPositions(e):null}setSkipCPUReadback(e){this.skipCPUPositionUpdate=e,this.simulation&&this.simulation.setSkipCPUReadback(e)}readBackPositions(){if(this.simulation){this.simulation.readBackPositions();let e=this.simulation.nodes(),t=this.params.dimensions??3;e.forEach(n=>{let i=this.nodeIdToIndex.get(n.id);if(i!==void 0&&i<this.graph.layoutNodes.length){let r=this.graph.layoutNodes[i];r&&(r.position.x=n.x??0,r.position.y=n.y??0,r.position.z=t>2?n.z??0:0)}})}}debugTick(){if(!this.simulation)return;this.simulation.nodes().length>0,this.simulation.tick(1),this.simulation.nodes().length>0,this.onTick()}debugZDistribution(){if(!this.simulation)return;let e=this.simulation.nodes();if(e.length===0)return;let t=1/0,n=-1/0,i=0,r=0,o=[];e.forEach(g=>{let m=g.z||0;t=Math.min(t,m),n=Math.max(n,m),i+=m,r++,o.push(m)});let a=i/r,s=n-t,l=0;o.forEach(g=>{l+=Math.pow(g-a,2)});let u=Math.sqrt(l/r),c=s*.1,d=o.filter(g=>Math.abs(g-t)<c).length,f=o.filter(g=>Math.abs(g-n)<c).length,p=(d+f)/r}},Dt=class{constructor(e){this.c=e,this.mode="gpu"}getPositionTexture(){return this.c.getPositionTexture()}getTextureSize(){return this.c.getTextureSize()}getSpaceSize(){return this.c.getSpaceSize()}tick(){}start(){this.c.startLayout()}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)}transitionDimensions(e,t){this.c.transitionDimensions(e,t)}getDimensions(){return this.c.getDimensions()}updateOption(e,t){this.c.updateLayoutOption(e,t)}};function Vn(e){let{backend:t="auto",renderer:n,config:i,graph:r,autoStart:o=!0}=e,a;t==="webgpu"?Pe()?a="webgpu":(console.warn('[createForceLayout] backend="webgpu" requested but navigator.gpu is unavailable; falling back to WebGL.'),a="webgl"):t==="webgl"?a="webgl":a=Pe()?"webgpu":"webgl";let s=r??{layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!0};if(a==="webgpu"){let l=new ot(s);l.config(i);let u=new st(l);return o&&l.startLayout(),{controller:l,adapter:u,backend:"webgpu"}}else{let l=new It(s,n);l.config(i);let u=new Dt(l);return o&&l.startLayout(),{controller:l,adapter:u,backend:"webgl"}}}function Kr(e,t){let n=new Map(e.nodes.map(a=>[a.id,{...a}])),i=new Map(e.edges.map(a=>[a.id,{...a}]));for(let a of t.addNodes??[])n.set(a.id,a);for(let a of t.addEdges??[])i.set(a.id,a);for(let a of t.updateNodes??[]){let s=n.get(a.id);s&&n.set(a.id,{...s,...a.changes})}for(let a of t.updateEdges??[]){let s=i.get(a.id);s&&i.set(a.id,{...s,...a.changes})}for(let a of t.removeNodeIds??[])n.delete(a);for(let a of t.removeEdgeIds??[])i.delete(a);for(let a of t.positionPatches??[]){let s=n.get(a.id);s&&n.set(a.id,{...s,position:a.position})}for(let a of t.pinPatches??[]){let s=n.get(a.id);if(s){let l={...s,pinned:a.pinned};a.position&&(l.position=a.position),n.set(a.id,l)}}let r=Array.from(n.values()).map((a,s)=>({...a,index:s})),o=Array.from(i.values()).map((a,s)=>({...a,index:s}));return{...e,version:t.graphVersion,nodes:r,edges:o}}var Wn=class{constructor(e,t,n={}){this.mode="gpu",this._status="idle",this._snapshot=null,this._tickCount=0,this._listeners=new Map,this.id=e,this.controller=t,this._settings={dimensions:3,...n}}get status(){return this._status}getCapabilities(){return{mode:"gpu",supportsGpuTexture:!0,supportsCpuReadback:!1,supportsIncrementalDelta:!1,supportsPinning:!0,supportsDimensions:!0}}init(e,t){this._status!=="disposed"&&(this._snapshot=e,t&&(this._settings={...this._settings,...t}),this._feedSnapshotToController(e),this._status="idle")}applyDelta(e){if(!this._snapshot||this._status==="disposed")return;this._snapshot=Kr(this._snapshot,e);let t=this._status==="running";this._feedSnapshotToController(this._snapshot),t&&this._controllerStart()}tick(e){this._tickCount++,this.controller.tick&&this.controller.tick();let t=this._readNeedsUpdate(),n={tick:this._tickCount,didChangePositions:t,alpha:void 0};return this._emit("tick",n),n}start(){this._status!=="disposed"&&(this._controllerStart(),this._status="running",this._emit("started",{}))}stop(){this._status!=="disposed"&&(this._controllerStop(),this._status="stopped",this._emit("stopped",{}))}dispose(){this._controllerStop(),typeof this.controller.dispose=="function"?this.controller.dispose():typeof this.controller.destroy=="function"&&this.controller.destroy(),this._status="disposed",this._snapshot=null,this._listeners.clear()}getSettings(){return{...this._settings}}updateSettings(e){this._settings={...this._settings,...e}}setDimensions(e){this._settings={...this._settings,dimensions:e},typeof this.controller.transitionDimensions=="function"&&this.controller.transitionDimensions(e)}getReadback(){return{positions:null,texture:this.controller.getPositionTexture(),textureSize:this.controller.getTextureSize(),spaceSize:this.controller.getSpaceSize()}}getNodePosition(e){return null}setNodePosition(e,t){}pinNodes(e){this._status!=="disposed"&&typeof this.controller.pinNodes=="function"&&this.controller.pinNodes(e)}unpinNodes(e){this._status!=="disposed"&&typeof this.controller.unpinNodes=="function"&&this.controller.unpinNodes(e)}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}_feedSnapshotToController(e){this._settings={...this._settings,dimensions:e.dimensions},typeof this.controller.startLayout=="function"&&this.controller.startLayout()}_controllerStart(){typeof this.controller.startLayout=="function"?this.controller.startLayout():typeof this.controller.start=="function"&&this.controller.start()}_controllerStop(){typeof this.controller.stopLayout=="function"?this.controller.stopLayout():typeof this.controller.stop=="function"&&this.controller.stop()}_readNeedsUpdate(){return this.controller.needsUpdate!==void 0?!!this.controller.needsUpdate:this.controller.graph!==void 0?!!this.controller.graph.renderNeedsUpdate:!1}_emit(e,t){this._listeners.get(e)?.forEach(n=>n(t))}};
|
|
2327
|
+
`;function ha(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,f=null,d=null,p=null;function m(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&g()}function g(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!d||!p){w(h);return}M(h,v,b)}function w(h){for(let v=0;v<t.length;v++){let b=t[v];b.vx+=(o[v]-(b.x||0))*r[v]*h}}function M(h,v,b){d.uniforms.positionTexture.value=v,d.uniforms.targetTexture.value=p,d.uniforms.alpha.value=h,d.uniforms.textureSize.value=u,d.uniforms.nodeCount.value=c,d.uniforms.axis.value=0;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,m()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&m();let v=u*u,b=new Float32Array(v*4),x=0,C=0;for(let E=0;E<t.length;E++){let A=E*4;b[A]=o[E]??0,b[A+1]=r[E]??0,b[A+2]=0,b[A+3]=0,E<10&&(x+=r[E]??0,C+=o[E]??0)}p?.dispose(),p=new ae.DataTexture(b,u,u,ae.RGBAFormat,ae.FloatType),p.minFilter=ae.NearestFilter,p.magFilter=ae.NearestFilter,p.needsUpdate=!0,s=new ae.Scene,d=new ae.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:0}},vertexShader:he,fragmentShader:Lt,blending:ae.AdditiveBlending,depthTest:!1,depthWrite:!1}),f=new ae.Mesh(ye(),d),s.add(f)},y.dispose=function(){p?.dispose(),d?.dispose(),f&&(f.geometry.dispose(),s?.remove(f))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),m(),y)},y.x=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),m(),y)},y}function ma(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,f=null,d=null,p=null;function m(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&g()}function g(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!d||!p){w(h);return}M(h,v,b)}function w(h){for(let v=0;v<t.length;v++){let b=t[v];b.vy+=(o[v]-(b.y||0))*r[v]*h}}function M(h,v,b){d.uniforms.positionTexture.value=v,d.uniforms.targetTexture.value=p,d.uniforms.alpha.value=h,d.uniforms.textureSize.value=u,d.uniforms.nodeCount.value=c,d.uniforms.axis.value=1;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,m()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&m();let v=u*u,b=new Float32Array(v*4),x=0,C=0;for(let E=0;E<t.length;E++){let A=E*4,R=o[E]??0,I=r[E]??0;b[A]=R,b[A+1]=I,b[A+2]=0,b[A+3]=0,E<10&&(x+=R,C+=I)}t.length>0,p?.dispose(),p=new oe.DataTexture(b,u,u,oe.RGBAFormat,oe.FloatType),p.minFilter=oe.NearestFilter,p.magFilter=oe.NearestFilter,p.needsUpdate=!0,s=new oe.Scene,d=new oe.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:1}},vertexShader:he,fragmentShader:Lt,blending:oe.AdditiveBlending,depthTest:!1,depthWrite:!1}),f=new oe.Mesh(ye(),d),s.add(f)},y.dispose=function(){p?.dispose(),d?.dispose(),f&&(f.geometry.dispose(),s?.remove(f))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),m(),y)},y.y=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),m(),y)},y}function ga(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,f=null,d=null,p=null;function m(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&g()}function g(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!d||!p){w(h);return}M(h,v,b)}function w(h){for(let v=0;v<t.length;v++){let b=t[v];b.vz+=(o[v]-(b.z||0))*r[v]*h}}function M(h,v,b){d.uniforms.positionTexture.value=v,d.uniforms.targetTexture.value=p,d.uniforms.alpha.value=h,d.uniforms.textureSize.value=u,d.uniforms.nodeCount.value=c,d.uniforms.axis.value=2;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,m()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&m();let v=u*u,b=new Float32Array(v*4);for(let x=0;x<t.length;x++){let C=x*4;b[C]=o[x]??0,b[C+1]=r[x]??0,b[C+2]=0,b[C+3]=0}p?.dispose(),p=new se.DataTexture(b,u,u,se.RGBAFormat,se.FloatType),p.minFilter=se.NearestFilter,p.magFilter=se.NearestFilter,p.needsUpdate=!0,s=new se.Scene,d=new se.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:2}},vertexShader:he,fragmentShader:Lt,blending:se.AdditiveBlending,depthTest:!1,depthWrite:!1}),f=new se.Mesh(ye(),d),s.add(f)},y.dispose=function(){p?.dispose(),d?.dispose(),f&&(f.geometry.dispose(),s?.remove(f))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),m(),y)},y.z=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),m(),y)},y}var ht={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},Gt=class{constructor(e,t){if(this.simulation=null,this.getOptions=null,this._enable=!0,this._isFinish=!1,this.nodeIdToIndex=new Map,this.lastUpdateTime=0,this.updateIntervalMs=1e3/24,this.skipCPUPositionUpdate=!1,this._dimTransition=null,this._gpuZZeroed=!1,this.graph=e,t)this.renderer=t;else{let n=document.createElement("canvas");n.style.display="none",this.renderer=new ui.WebGLRenderer({canvas:n,alpha:!0,antialias:!1}),this.renderer.setSize(256,256)}this.params={...ht}}config(e){if(this.getOptions=e,e){let t=e();t&&this.applyConfig(t)}return this}configure(e){return this.config(e)}applyConfig(e){e.friction!==void 0&&e.velocityDecay===void 0&&(e.velocityDecay=e.friction),Object.assign(this.params,e)}calculateForces(){let e=this.params.heightCompress??1,t=this.params.gravity??.1,n=this.params.dimensions??3,i,r,o,a;return n===2?(r=t*1.5,i=0,o=.02,a=.8):(i=t*Math.sqrt(e),r=t/Math.sqrt(e),i=i>10?10:i,o=ht.alphaDecay??.1,a=ht.alpha??.6),{forcexy:r,forcez:i,alphaDecay:o,alpha:a}}startLayout(e=0,t=0,n=!1){let i=this.params.dimensions;if(this.getOptions){let _=this.getOptions();_&&this.applyConfig(_)}this.params.dimensions=i,this._gpuZZeroed=!1;let r=this.graph.layoutNodes||[],o=this.graph.layoutEdges||[];if(r.length===0)return;this.nodeIdToIndex.clear(),r.forEach((_,z)=>{this.nodeIdToIndex.set(_.id,z)});let a=this.params.dimensions??3;this.params.dimensions=a;let s=r.some(_=>Math.abs(_.position.z)>1e-6),l=Math.cbrt(r.length)*2,u=a>2&&!s&&!n,c=r.map((_,z)=>{let P=_.position.x,T=_.position.y,k=a<=2?0:_.position.z;if(u&&!_.pinned){let q=Math.random(),N=Math.random(),G=Math.random(),S=2*Math.PI*q,D=Math.acos(2*N-1),O=Math.cbrt(G)*l;P=O*Math.sin(D)*Math.cos(S),T=O*Math.sin(D)*Math.sin(S),k=O*Math.cos(D)}return{..._,index:z,x:P,y:T,z:k,vx:0,vy:0,vz:0,fx:_.pinned?_.position.x:null,fy:_.pinned?_.position.y:null,fz:_.pinned?_.position.z:null}}),f=o.filter(_=>{let z=this.nodeIdToIndex.get(_.sourceId),P=this.nodeIdToIndex.get(_.targetId);return z!==void 0&&P!==void 0}).map(_=>({source:_.sourceId,target:_.targetId}));this.simulation&&(this.simulation.stop(),this.simulation.dispose()),this.simulation=Kr(c,a,this.renderer);let{forcexy:d,forcez:p,alphaDecay:m,alpha:g}=this.calculateForces(),y=this.params.charge??-.01,w=r.length,M=this.params.gravityX??1,h=this.params.gravityY??1,v=this.params.gravityZ??1,b=this.params.linkDistance??.5,x=this.params.linkStrength??1,C=d*this.params.gravityX,E=d*this.params.gravityY,A=p*this.params.gravityZ,R=ha(0).strength(C),I=ma(0).strength(E);if(this.simulation.force("x",R),this.simulation.force("y",I),a>2){let _=ga(0).strength(A);this.simulation.force("z",_)}if(this.simulation.force("center",na(0,0,0).strength(1)),a>2){let _=ca();_.strength(y);let z=this.params.octreeTheta??.8,P=r.length,T=Math.max(.2,Math.min(1,1.2-.1*Math.log10(Math.max(P,1)))),k=z*T;_.theta(k);let q=this.params.octreeLevels;q!==void 0&&_.maxLevels(q),this.simulation.force("charge",_)}else{let _=oa();_.strength(y);let z=this.params.quadtreeTheta??.9,P=Math.max(.5,Math.min(1,500/Math.sqrt(r.length))),T=z*P;_.theta(T),this.simulation.force("charge",_)}if(f.length>0){let _=pa(f);_.distance(b),_.strength(x),_.id(z=>z.id),this.simulation.force("link",_)}(this.params.collision??.15)>0;let B=this.params.velocityDecay??ht.velocityDecay;this.simulation.alpha(g).alphaMin(.001).alphaDecay(m).velocityDecay(B),this.simulation.on("tick",()=>{this.onTick()}),this.simulation.on("end",()=>{this._isFinish=!0,this.graph.renderNeedsUpdate=!1}),this._isFinish=!1,this._enable=!0,this.graph.renderNeedsUpdate=!0,this.skipCPUPositionUpdate&&this.simulation.setSkipCPUReadback(!0),this.simulation.restart()}onTick(){if(!this._enable||!this.simulation)return;if(this.skipCPUPositionUpdate){(this.params.dimensions??3)<=2&&this.ensureGPUZeroZ(),this.graph.renderNeedsUpdate=!0;return}let e=performance.now();if(e-this.lastUpdateTime<this.updateIntervalMs)return;this.lastUpdateTime=e;let t=this.simulation.nodes(),n=this.params.dimensions??3;t.forEach(i=>{let r=this.nodeIdToIndex.get(i.id);if(r!==void 0&&r<this.graph.layoutNodes.length){let o=this.graph.layoutNodes[r];o&&!o.pinned&&i.fx==null&&(o.position.x=i.x??0,o.position.y=i.y??0,n>2?o.position.z=i.z??0:o.position.z=0,o.isPositionDirty=!0)}}),this.graph.renderNeedsUpdate=!0}ensureGPUZeroZ(){if(this._gpuZZeroed||!this.simulation)return;this._gpuZZeroed=!0,this.simulation.readBackPositions();let e=this.simulation.nodes(),t=[];e.forEach((i,r)=>{Math.abs(i.z??0)>1e-6&&t.push({index:r,x:i.x??0,y:i.y??0,z:0})}),t.length>0&&this.simulation.uploadNodePositions(t);let n=this.graph.layoutNodes;for(let i=0;i<n.length;i++)n[i].position.z=0}restartLayout(){if(!this.simulation||!this._enable)return;if(this.getOptions){let w=this.getOptions();w&&this.applyConfig(w)}let e=this.params.dimensions??3,{forcexy:t,forcez:n,alphaDecay:i,alpha:r}=this.calculateForces(),o=this.params.charge??-.01,a=this.params.linkDistance??.5,s=this.params.linkStrength??1,l=t*(this.params.gravityX??1),u=t*(this.params.gravityY??1),c=n*(this.params.gravityZ??1),f=this.simulation.force("x"),d=this.simulation.force("y"),p=this.simulation.force("z"),m=this.simulation.force("charge"),g=this.simulation.force("link");f&&f.strength(l),d&&d.strength(u),p&&e>2&&p.strength(c),m&&m.strength(o),g&&(g.distance(a),g.strength(s));let y=this.params.velocityDecay??.3;this.simulation.alpha(r).alphaDecay(i).velocityDecay(y).restart(),this._isFinish=!1,this.graph.renderNeedsUpdate=!0}stopLayout(){this.simulation&&this.simulation.stop(),this._isFinish=!0,this.graph.renderNeedsUpdate=!1}updateLayoutOption(e,t){if(e==="friction"?this.params.velocityDecay=t:this.params[e]=t,!this.simulation||!this._enable)return;let n=this.simulation.force("charge"),i=this.simulation.force("link"),r=this.simulation.force("x"),o=this.simulation.force("y"),a=this.simulation.force("z");switch(e){case"charge":n&&(n.strength(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"linkDistance":i&&(i.distance(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"linkStrength":i&&(i.strength(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"gravity":case"gravityX":case"gravityY":case"gravityZ":case"heightCompress":let{forcexy:s,forcez:l}=this.calculateForces(),u=s*(this.params.gravityX??1),c=s*(this.params.gravityY??1),f=l*(this.params.gravityZ??1);r&&r.strength(u),o&&o.strength(c),a&&a.strength(f),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart();break;case"velocityDecay":case"friction":this.simulation.velocityDecay(this.params.velocityDecay??.3);break;case"alpha":case"alphaDecay":this.restartLayout();break;default:this.restartLayout();break}this.graph.renderNeedsUpdate=!0}pinNodes(e){if(!this.simulation)return;let t=this.simulation.nodes(),n=[];e.forEach(r=>{let o=this.nodeIdToIndex.get(r.id);if(o!==void 0){let a=this.graph.layoutNodes[o];a&&(a.pinned=!0);let s=t[o];s&&(s.fx=r.position.x,s.fy=r.position.y,s.fz=r.position.z,n.push({index:o,x:r.position.x,y:r.position.y,z:r.position.z}))}}),n.length>0&&this.simulation.uploadNodePositions(n);let i=n.map(r=>({index:r.index,isPinned:!0}));this.simulation.updatePinnedNodes(i),this._enable&&this.simulation.alpha()<.1&&this.simulation.alpha(.3).restart(),this.graph.renderNeedsUpdate=!0}unpinNodes(e){if(!this.simulation)return;let t=this.simulation.nodes(),n=[];for(let i of e){let r=this.nodeIdToIndex.get(i);if(r===void 0)continue;let o=this.graph.layoutNodes[r];o&&(o.pinned=!1);let a=t[r];a&&(a.fx=null,a.fy=null,a.fz=null),n.push({index:r,isPinned:!1})}n.length>0&&this.simulation.updatePinnedNodes(n),this._enable&&this.simulation.alpha()<.05&&this.simulation.alpha(.15).restart(),this.graph.renderNeedsUpdate=!0}set enable(e){this._enable=e,!e&&this.simulation&&this.simulation.stop(),this._isFinish=!e,this.graph.renderNeedsUpdate=e}get enable(){return this._enable}get isFinish(){return this._isFinish}setExpectedNodeCount(e){}clearExpectedNodeCount(){}updateGraph(e,t,n=!1){this.startLayout()}destroy(){this.cancelDimensionTransition(),this.simulation&&(this.simulation.stop(),this.simulation.dispose(),this.simulation=null)}transitionDimensions(e,t=600){(this.params.dimensions??3)!==e&&(e===2?this.transition3Dto2D(t):this.transition2Dto3D())}transition3Dto2D(e){this.readBackPositions(),this.params.dimensions=2,this.startLayout(0,0,!0)}transition2Dto3D(){this.readBackPositions(),this.params.dimensions=3,this.startLayout()}cancelDimensionTransition(){this._dimTransition=null}getDimensions(){return this.params.dimensions??3}debugNodePositions(){let e=this.simulation?this.simulation.nodes():[];if(this.simulation&&e.length>0)for(let n=0;n<Math.min(3,e.length);n++){let i=e[n]}let t=this.graph.layoutNodes||[];if(t.length>0){for(let n=0;n<Math.min(3,t.length);n++){let i=t[n]}if(this.simulation&&e.length>0)for(let n=0;n<Math.min(3,Math.min(e.length,t.length));n++){let i=e[n],r=t.find(o=>o.id===i.id);if(r){let o=Math.abs((i.x??0)-r.position.x)<.001&&Math.abs((i.y??0)-r.position.y)<.001&&Math.abs((i.z??0)-r.position.z)<.001}}}}getPositionTexture(){return this.simulation?this.simulation.getPositionTexture():null}getTextureSize(){return this.simulation?this.simulation.getTextureSize():0}getSpaceSize(){return this.simulation?this.simulation.getSpaceSize():10}debugGPUPositions(e=5){return this.simulation?this.simulation.debugPositions(e):null}setSkipCPUReadback(e){this.skipCPUPositionUpdate=e,this.simulation&&this.simulation.setSkipCPUReadback(e)}readBackPositions(){if(this.simulation){this.simulation.readBackPositions();let e=this.simulation.nodes(),t=this.params.dimensions??3;e.forEach(n=>{let i=this.nodeIdToIndex.get(n.id);if(i!==void 0&&i<this.graph.layoutNodes.length){let r=this.graph.layoutNodes[i];r&&(r.position.x=n.x??0,r.position.y=n.y??0,r.position.z=t>2?n.z??0:0)}})}}debugTick(){if(!this.simulation)return;this.simulation.nodes().length>0,this.simulation.tick(1),this.simulation.nodes().length>0,this.onTick()}debugZDistribution(){if(!this.simulation)return;let e=this.simulation.nodes();if(e.length===0)return;let t=1/0,n=-1/0,i=0,r=0,o=[];e.forEach(m=>{let g=m.z||0;t=Math.min(t,g),n=Math.max(n,g),i+=g,r++,o.push(g)});let a=i/r,s=n-t,l=0;o.forEach(m=>{l+=Math.pow(m-a,2)});let u=Math.sqrt(l/r),c=s*.1,f=o.filter(m=>Math.abs(m-t)<c).length,d=o.filter(m=>Math.abs(m-n)<c).length,p=(f+d)/r}},Nt=class{constructor(e){this.c=e,this.mode="gpu"}getPositionTexture(){return this.c.getPositionTexture()}getTextureSize(){return this.c.getTextureSize()}getSpaceSize(){return this.c.getSpaceSize()}tick(){}start(){this.c.startLayout()}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)}transitionDimensions(e,t){this.c.transitionDimensions(e,t)}getDimensions(){return this.c.getDimensions()}updateOption(e,t){this.c.updateLayoutOption(e,t)}};function ci(e){let{backend:t="auto",renderer:n,config:i,graph:r,autoStart:o=!0}=e,a;t==="webgpu"?Pe()?a="webgpu":(console.warn('[createForceLayout] backend="webgpu" requested but navigator.gpu is unavailable; falling back to WebGL.'),a="webgl"):t==="webgl"?a="webgl":a=Pe()?"webgpu":"webgl";let s=r??{layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!0};if(a==="webgpu"){let l=new ft(s);l.config(i);let u=new pt(l);return o&&l.startLayout(),{controller:l,adapter:u,backend:"webgpu"}}else{let l=new Gt(s,n);l.config(i);let u=new Nt(l);return o&&l.startLayout(),{controller:l,adapter:u,backend:"webgl"}}}function ya(e,t){let n=new Map(e.nodes.map(a=>[a.id,{...a}])),i=new Map(e.edges.map(a=>[a.id,{...a}]));for(let a of t.addNodes??[])n.set(a.id,a);for(let a of t.addEdges??[])i.set(a.id,a);for(let a of t.updateNodes??[]){let s=n.get(a.id);s&&n.set(a.id,{...s,...a.changes})}for(let a of t.updateEdges??[]){let s=i.get(a.id);s&&i.set(a.id,{...s,...a.changes})}for(let a of t.removeNodeIds??[])n.delete(a);for(let a of t.removeEdgeIds??[])i.delete(a);for(let a of t.positionPatches??[]){let s=n.get(a.id);s&&n.set(a.id,{...s,position:a.position})}for(let a of t.pinPatches??[]){let s=n.get(a.id);if(s){let l={...s,pinned:a.pinned};a.position&&(l.position=a.position),n.set(a.id,l)}}let r=Array.from(n.values()).map((a,s)=>({...a,index:s})),o=Array.from(i.values()).map((a,s)=>({...a,index:s}));return{...e,version:t.graphVersion,nodes:r,edges:o}}var di=class{constructor(e,t,n={}){this.mode="gpu",this._status="idle",this._snapshot=null,this._tickCount=0,this._listeners=new Map,this.id=e,this.controller=t,this._settings={dimensions:3,...n}}get status(){return this._status}getCapabilities(){return{mode:"gpu",supportsGpuTexture:!0,supportsCpuReadback:!1,supportsIncrementalDelta:!1,supportsPinning:!0,supportsDimensions:!0}}init(e,t){this._status!=="disposed"&&(this._snapshot=e,t&&(this._settings={...this._settings,...t}),this._feedSnapshotToController(e),this._status="idle")}applyDelta(e){if(!this._snapshot||this._status==="disposed")return;this._snapshot=ya(this._snapshot,e);let t=this._status==="running";this._feedSnapshotToController(this._snapshot),t&&this._controllerStart()}tick(e){this._tickCount++,this.controller.tick&&this.controller.tick();let t=this._readNeedsUpdate(),n={tick:this._tickCount,didChangePositions:t,alpha:void 0};return this._emit("tick",n),n}start(){this._status!=="disposed"&&(this._controllerStart(),this._status="running",this._emit("started",{}))}stop(){this._status!=="disposed"&&(this._controllerStop(),this._status="stopped",this._emit("stopped",{}))}dispose(){this._controllerStop(),typeof this.controller.dispose=="function"?this.controller.dispose():typeof this.controller.destroy=="function"&&this.controller.destroy(),this._status="disposed",this._snapshot=null,this._listeners.clear()}getSettings(){return{...this._settings}}updateSettings(e){this._settings={...this._settings,...e}}setDimensions(e){this._settings={...this._settings,dimensions:e},typeof this.controller.transitionDimensions=="function"&&this.controller.transitionDimensions(e)}getReadback(){return{positions:null,texture:this.controller.getPositionTexture(),textureSize:this.controller.getTextureSize(),spaceSize:this.controller.getSpaceSize()}}getNodePosition(e){return null}setNodePosition(e,t){}pinNodes(e){this._status!=="disposed"&&typeof this.controller.pinNodes=="function"&&this.controller.pinNodes(e)}unpinNodes(e){this._status!=="disposed"&&typeof this.controller.unpinNodes=="function"&&this.controller.unpinNodes(e)}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}_feedSnapshotToController(e){this._settings={...this._settings,dimensions:e.dimensions},typeof this.controller.startLayout=="function"&&this.controller.startLayout()}_controllerStart(){typeof this.controller.startLayout=="function"?this.controller.startLayout():typeof this.controller.start=="function"&&this.controller.start()}_controllerStop(){typeof this.controller.stopLayout=="function"?this.controller.stopLayout():typeof this.controller.stop=="function"&&this.controller.stop()}_readNeedsUpdate(){return this.controller.needsUpdate!==void 0?!!this.controller.needsUpdate:this.controller.graph!==void 0?!!this.controller.graph.renderNeedsUpdate:!1}_emit(e,t){this._listeners.get(e)?.forEach(n=>n(t))}};
|
|
2328
2328
|
//# sourceMappingURL=layout-gpu.js.map
|