semiotic 3.10.2 → 3.10.3
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/README.md +23 -27
- package/ai/artifact-surface-inventory.json +1 -1
- package/ai/behaviorContracts.cjs +1 -1
- package/ai/dist/mcp-server.js +1 -1
- package/ai/reference.md +4 -4
- package/ai/schema.json +1 -1
- package/ai/surface-manifest.json +1 -1
- package/ai/system-prompt.md +1 -1
- package/ai/task-packets/compare-category-totals.json +4 -4
- package/ai/task-packets/compare-category-totals.md +2 -2
- package/ai/task-packets/correct-published-chart.json +4 -4
- package/ai/task-packets/correct-published-chart.md +2 -2
- package/ai/task-packets/index.json +6 -6
- package/ai/task-packets/update-live-chart.json +4 -4
- package/ai/task-packets/update-live-chart.md +2 -2
- package/dist/{c-AKLBQMQF.min.js → c-43XNOQNQ.min.js} +50 -50
- package/dist/{c-PZ3NEGNG.min.js → c-5PIKBUMF.min.js} +1 -1
- package/dist/{c-FDUQDCBC.min.js → c-CO4NDAD6.min.js} +23 -23
- package/dist/c-FHNY57SO.min.js +209 -0
- package/dist/c-FMCUQ6JX.min.js +1 -0
- package/dist/{c-C4KIXUWU.min.js → c-GK263BF4.min.js} +1 -1
- package/dist/{c-TTKWXGAI.min.js → c-HNHKIMIV.min.js} +3 -3
- package/dist/c-IJCZGUG6.min.js +31 -0
- package/dist/{c-7LY46QUI.min.js → c-ISA6IJ6V.min.js} +7 -7
- package/dist/{c-4MD53L2J.min.js → c-JC76YAHB.min.js} +28 -28
- package/dist/{c-VXIYF7V2.min.js → c-JOPGDP6N.min.js} +1 -1
- package/dist/c-KXH7LFIL.min.js +26 -0
- package/dist/c-M43PK7K4.min.js +1 -0
- package/dist/{c-7ASK4WBF.min.js → c-PITYSOPK.min.js} +1 -1
- package/dist/{c-2TW5H5PD.min.js → c-QPO24R7Q.min.js} +1 -1
- package/dist/{c-KGROWFT2.min.js → c-SAP5KY6R.min.js} +2 -2
- package/dist/c-UMGHCBH5.min.js +114 -0
- package/dist/{c-6ZU3QVLB.min.js → c-VEMCBQZZ.min.js} +33 -33
- package/dist/{c-IPYGNVN6.min.js → c-WD2RL76M.min.js} +45 -45
- package/dist/{c-PQOZPM4G.min.js → c-YL7HJL5J.min.js} +1 -1
- package/dist/c-Z6GRGS53.min.js +1 -0
- package/dist/{c-SG2Y7EBY.min.js → c-ZVOFLE2P.min.js} +6 -6
- package/dist/components/CategoryColors.d.ts +7 -0
- package/dist/components/LinkedCharts.d.ts +2 -1
- package/dist/components/charts/shared/useChartSetup.d.ts +1 -1
- package/dist/components/charts/shared/useNetworkChartSetup.d.ts +1 -1
- package/dist/components/data/transforms.d.ts +1 -0
- package/dist/geo.min.js +3 -3
- package/dist/geo.module.min.js +10 -10
- package/dist/network.module.min.js +1 -1
- package/dist/ordinal.module.min.js +1 -1
- package/dist/physics.module.min.js +1 -1
- package/dist/physicsWorker.js +1 -1
- package/dist/semiotic-ai-core.min.js +1 -1
- package/dist/semiotic-ai-core.module.min.js +1 -1
- package/dist/semiotic-ai.module.min.js +7 -7
- package/dist/semiotic-artifact.min.js +1 -1
- package/dist/semiotic-artifact.module.min.js +1 -1
- package/dist/semiotic-atlas-selection.module.min.js +1 -1
- package/dist/semiotic-client-cjs-shared.min.js +903 -902
- package/dist/semiotic-data.min.js +1 -1
- package/dist/semiotic-data.module.min.js +1 -1
- package/dist/semiotic-experimental-auxiliary.module.min.js +2 -2
- package/dist/semiotic-experimental-node-auxiliary.module.min.js +2 -2
- package/dist/semiotic-line.module.min.js +1 -1
- package/dist/semiotic-realtime-core.module.min.js +1 -1
- package/dist/semiotic-recipes-core-cjs-base.min.js +1 -1
- package/dist/semiotic-recipes-core.module.min.js +1 -1
- package/dist/semiotic-server-edge-node.module.min.js +65 -65
- package/dist/semiotic-server-edge.min.js +64 -64
- package/dist/semiotic-server-edge.module.min.js +80 -80
- package/dist/semiotic-server-node.min.js +64 -64
- package/dist/semiotic-server-node.module.min.js +1 -1
- package/dist/semiotic.module.min.js +10 -10
- package/dist/server.min.js +64 -64
- package/dist/server.module.min.js +1 -1
- package/dist/xy.module.min.js +1 -1
- package/package.json +5 -5
- package/dist/c-72CBVNYX.min.js +0 -209
- package/dist/c-F2GGJB2S.min.js +0 -31
- package/dist/c-G53AVC42.min.js +0 -113
- package/dist/c-HQ27AHMC.min.js +0 -1
- package/dist/c-IHWZ2C6D.min.js +0 -26
- package/dist/c-MOP2NGLH.min.js +0 -1
- package/dist/c-PKY4JFY5.min.js +0 -1
package/dist/physicsWorker.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}function t(e){const t=e.fixedPosition;Number.isFinite(t?.x)&&(e.x=e.prevX=t.x,e.vx=0),Number.isFinite(t?.y)&&(e.y=e.prevY=t.y,e.vy=0)}function s(e){if(!e)return;const t=Number.isFinite(e.x)?e.x:void 0,s=Number.isFinite(e.y)?e.y:void 0;return null==t&&null==s?void 0:{x:t,y:s}}function i(e,t,s){const i="x"===s?"y":"x",n=Math.abs(t[s]-e[s]),o=t[i]-e[i],r=(e,t)=>"circle"===e.shape.type?e.shape.radius:("x"===t?e.shape.width:e.shape.height)/2;let a;if("circle"===e.shape.type&&"circle"===t.shape.type){const s=e.shape.radius+t.shape.radius;a=Math.sqrt(Math.max(0,s*s-n*n))}else if("aabb"===e.shape.type&&"aabb"===t.shape.type)a=r(e,i)+r(t,i);else{const o="circle"===e.shape.type?e:t,d="aabb"===e.shape.type?e:t,h=r(o,s),c=Math.max(0,n-r(d,s));a=r(d,i)+Math.sqrt(Math.max(0,h*h-c*c))}const d=o<0?-1:1;return{nx:"x"===i?d:0,ny:"y"===i?d:0,penetration:Math.max(0,a-Math.abs(o))}}function n(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function o(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function r(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,...e.fixedPosition?{fixedPosition:s(e.fixedPosition)}:{},shape:n(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function a(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function d(e){return{id:e.id,shape:o(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:a(e.bodyFilter),index:e.index}}var h={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},c=1e-9,l=.005;function u(e,t,s){return Math.max(t,Math.min(s,e))}function p(e,t,s){return Math.min(e??s,t??s)}function v(e,t,s){return u(Math.max(e??s,t??s),0,1)}function y(e){return e<0?-1:1}function f(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,s=e.shape.height/2;return{minX:e.x-t,minY:e.y-s,maxX:e.x+t,maxY:e.y+s}}function m(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,s=t.height/2;return{minX:t.x-e,minY:t.y-s,maxX:t.x+e,maxY:t.y+s}}const s=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-s,minY:Math.min(t.y1,t.y2)-s,maxX:Math.max(t.x1,t.x2)+s,maxY:Math.max(t.y1,t.y2)+s}}function x(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function b(e,t,s,i,n,o,r,a){const d=n-e,h=(s+r)/2-Math.abs(d);if(h<=0)return null;const c=o-t,l=(i+a)/2-Math.abs(c);return l<=0?null:h<l?{nx:y(d),ny:0,penetration:h}:{nx:0,ny:y(c),penetration:l}}function g(e,t,s,i,n,o,r){const a=o/2,d=r/2,h=e-u(e,i-a,i+a),l=t-u(t,n-d,n+d),p=h*h+l*l;if(p>s*s)return null;if(p<=c){const o=Math.abs(e-(i-a)),r=Math.abs(e-(i+a)),h=Math.abs(t-(n-d)),c=Math.abs(t-(n+d)),l=Math.min(o,r,h,c);return l===o?{nx:-1,ny:0,penetration:s+o}:l===r?{nx:1,ny:0,penetration:s+r}:l===h?{nx:0,ny:-1,penetration:s+h}:{nx:0,ny:1,penetration:s+c}}const v=Math.sqrt(p);return{nx:h/v,ny:l/v,penetration:s-v}}function S(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,s,i,n,o){const r=i-e,a=n-t,d=s+o,h=r*r+a*a;if(h>=d*d)return null;if(h<=c)return{nx:1,ny:0,penetration:d};const l=Math.sqrt(h);return{nx:r/l,ny:a/l,penetration:d-l}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return b(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const s=g(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return s?{nx:-s.nx,ny:-s.ny,penetration:s.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?g(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function w(e,t){const s=t.shape;if("aabb"===s.type)return"circle"===e.shape.type?g(e.x,e.y,e.shape.radius,s.x,s.y,s.width,s.height):b(s.x,s.y,s.width,s.height,e.x,e.y,e.shape.width,e.shape.height);const i="circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2;return function(e,t,s,i,n,o,r,a=0){const d=o-i,h=r-n,l=d*d+h*h,p=l<=c?0:u(((e-i)*d+(t-n)*h)/l,0,1),v=s+a/2,y=e-(i+d*p),f=t-(n+h*p),m=y*y+f*f;if(m>=v*v)return null;if(m<=c){const e=Math.sqrt(l);return e<=c?{nx:1,ny:0,penetration:v}:{nx:-h/e,ny:d/e,penetration:v}}const x=Math.sqrt(m);return{nx:y/x,ny:f/x,penetration:v-x}}(e.x,e.y,i,s.x1,s.y1,s.x2,s.y2,s.thickness??0)}function I(e,t){return`${e}\0${t}`}function B(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function M(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function O(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const s=function(e,t){if(!t)return;let s=e;for(const e of t.split(".")){if(null==s||"object"!=typeof s)return;if(!Object.prototype.hasOwnProperty.call(s,e))return;s=s[e]}return s}(e,t.property);return!("equals"in t&&!Object.is(s,t.equals))&&((!("notEquals"in t)||!Object.is(s,t.notEquals))&&(!(t.oneOf&&!M(s,t.oneOf))&&(!t.notOneOf||!M(s,t.notOneOf))))}function q(e,t){return O(t,e.bodyFilter)}var k=class{constructor(t={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...h,...t},this.random=e(this.options.seed)}init(t={}){this.options={...h,...t},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const i={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(c,e.mass??1),bodyCollisions:e.bodyCollisions??!0,...e.fixedPosition?{fixedPosition:s(e.fixedPosition)}:{},shape:n(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};t(i),this.nextBodyIndex+=1,this.bodies.set(e.id,i)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))B(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:o(t.shape),bodyFilter:a(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??`spring-${this.nextSpringIndex}`;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,s,i){const n=this.bodies.get(e);n&&(n.vx+=s/n.mass,n.vy+=i/n.mass,t(n),this.wake(n))}step(e=this.options.fixedDt){const s=Math.max(0,e);if(this.lastEvents=[],0===s)return;const i=this.sortedBodies();for(const e of i)e.prevX=e.x,e.prevY=e.y;this.applySprings(s);const n=this.options.maxVelocity;for(const e of i)if(!e.sleeping){if(e.vx+=this.options.gravity.x*s,e.vy+=this.options.gravity.y*s,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,t(e),n>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>n){const s=n/t;e.vx*=s,e.vy*=s}}e.x+=e.vx*s,e.y+=e.vy*s}this.supportedThisStep.clear();const o=this.bodyPairKeys(i),r=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;e<this.options.collisionIterations;e+=1)this.resolveBodyPairs(i,o,0===e),this.resolveColliders(i,r,0===e);this.updateSensors(i),this.updateSleeping(i,s)}settle(e=1200,t=this.options.fixedDt){let s=0;for(;s<e&&!this.allSleeping();)this.step(t),s+=1;return s}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,...t.fixedPosition?{fixedPosition:s(t.fixedPosition)}:{},shape:n(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(B)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(r),colliders:this.sortedColliders().map(d),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(s){this.options={...s.options,gravity:{...s.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(s.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of s.bodies){const s=r(e);t(s),this.bodies.set(s.id,s),this.nextBodyIndex=Math.max(this.nextBodyIndex,s.index+1)}this.nextColliderIndex=0;for(const e of s.colliders){const t=d(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of s.springs){this.springs.set(e.id,{...e,target:{...e.target}});const t=/^spring-(\d+)$/.exec(e.id);t&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(t[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const s=this.bodies.get(t.bodyId);if(!s||s.sleeping)continue;const i="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!i)continue;const n=i.x-s.x,o=i.y-s.y,r=n*n+o*o,a=Math.sqrt(r);if(a<=c)continue;const d=n/a,h=o/a,l="vx"in i?i.vx:0,u="vy"in i?i.vy:0,p=(l-s.vx)*d+(u-s.vy)*h,v=(a-t.restLength)*t.stiffness+p*t.damping;s.vx+=v*d*e/s.mass,s.vy+=v*h*e/s.mass}}resolveBodyPairs(e,t,s){for(const i of t){const[t,n]=i.split(":").map(Number),o=e[t],r=e[n];if(!o||!r)continue;const a=S(o,r);a&&(this.resolveDynamicCollision(o,r,a),s&&this.lastEvents.push({type:"contact",bodyId:o.id,otherId:r.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),s=new Map;for(let i=0;i<e.length;i+=1){if(!1===e[i].bodyCollisions)continue;const n=f(e[i]),o=Math.floor(n.minX/t),r=Math.floor(n.maxX/t),a=Math.floor(n.minY/t),d=Math.floor(n.maxY/t);for(let e=o;e<=r;e+=1)for(let t=a;t<=d;t+=1){const n=`${e}:${t}`,o=s.get(n);o?o.push(i):s.set(n,[i])}}const i=new Set;for(const t of Array.from(s.keys()).sort()){const n=s.get(t)??[];n.sort((e,t)=>e-t);for(let t=0;t<n.length;t+=1)for(let s=t+1;s<n.length;s+=1){const o=n[t],r=n[s];!1!==e[o].bodyCollisions&&!1!==e[r].bodyCollisions&&(x(f(e[o]),f(e[r]))&&i.add(`${o}:${r}`))}}return Array.from(i).sort((e,t)=>{const[s,i]=e.split(":").map(Number),[n,o]=t.split(":").map(Number);return s===n?i-o:s-n})}resolveDynamicCollision(e,t,s){(e.fixedPosition||t.fixedPosition)&&(!e.sleeping&&null==e.fixedPosition?.x||!t.sleeping&&null==t.fixedPosition?.x?!e.sleeping&&null==e.fixedPosition?.y||!t.sleeping&&null==t.fixedPosition?.y||(s=i(e,t,"y")):s=i(e,t,"x")),e.sleeping&&this.contactOpposesGravity(s.nx,s.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-s.nx,-s.ny)&&this.supportedThisStep.add(e.id);const n=e.sleeping?0:1/e.mass,o=t.sleeping?0:1/t.mass,r=null==e.fixedPosition?.x?n:0,a=null==e.fixedPosition?.y?n:0,d=null==t.fixedPosition?.x?o:0,h=null==t.fixedPosition?.y?o:0,u=e.fixedPosition||t.fixedPosition?s.nx**2*(r+d)+s.ny**2*(a+h):n+o;if(u<=c)return;const v=Math.max(0,s.penetration-l)/u;e.x-=s.nx*v*r,e.y-=s.ny*v*a,t.x+=s.nx*v*d,t.y+=s.ny*v*h;const y=t.vx-e.vx,f=t.vy-e.vy,m=y*s.nx+f*s.ny;if(m>0)return;const x=Math.abs(m),b=-(1+p(e.restitution,t.restitution,this.options.restitution))*m/u,g=b*s.nx,S=b*s.ny;e.vx-=g*r,e.vy-=S*a,t.vx+=g*d,t.vy+=S*h,this.applyFriction(e,t,s,b,n,o),x>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,s,i,n,o){const r=-s.ny,a=s.nx,d=(t.vx-e.vx)*r+(t.vy-e.vy)*a,h=null==e.fixedPosition?.x?n:0,l=null==e.fixedPosition?.y?n:0,p=null==t.fixedPosition?.x?o:0,y=null==t.fixedPosition?.y?o:0,f=e.fixedPosition||t.fixedPosition?r**2*(h+p)+a**2*(l+y):n+o;if(Math.abs(d)<=c||f<=c)return;const m=v(e.friction,t.friction,this.options.friction),x=u(-d/f,-i*m,i*m),b=x*r,g=x*a;e.vx-=b*h,e.vy-=g*l,t.vx+=b*p,t.vy+=g*y}resolveColliders(e,t,s){for(const i of e)for(const e of t){if(!q(e,i))continue;if(!x(f(i),m(e)))continue;const t=w(i,e);t&&(this.resolveStaticCollision(i,e,t),this.contactOpposesGravity(t.nx,t.ny)&&this.supportedThisStep.add(i.id),s&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,s,i){e.x+=i.nx*Math.max(0,i.penetration-l),e.y+=i.ny*Math.max(0,i.penetration-l);const n=e.vx*i.nx+e.vy*i.ny;if(n<0){const t=p(e.restitution,s.restitution,this.options.restitution);e.vx-=(1+t)*n*i.nx,e.vy-=(1+t)*n*i.ny;const o=-i.ny,r=i.nx,a=e.vx*o+e.vy*r,d=v(e.friction,s.friction,this.options.friction);e.vx-=a*o*d,e.vy-=a*r*d}t(e)}updateSensors(e){const t=new Set,s=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=f(i);for(const n of s){if(!q(n,i))continue;if(!x(e,m(n)))continue;if(!w(i,n))continue;const s=I(n.id,i.id);t.add(s),this.activeSensors.has(s)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:n.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:s,bodyId:i}=B(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:s})}this.activeSensors=t}updateSleeping(e,t){const s=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e){const e=Math.sqrt(i.vx*i.vx+i.vy*i.vy),n=Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY));!(e<this.options.sleepSpeed&&n<this.options.sleepSpeed*t)||s&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,!i.sleeping&&i.sleepTime>=this.options.sleepAfter&&(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}}contactOpposesGravity(e,t){const{x:s,y:i}=this.options.gravity,n=Math.hypot(s,i);return n<=1e-9||(e*s+t*i)/n<-.2}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},P=class{constructor(e={}){this.id="builtin",this.capabilities={...(new k).capabilities,engine:"builtin"},this.world=new k(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function C(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new P(e)}(t)}var T=["binId","targetBin","category","windowIndex","lane","group"];function A(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function D(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const s=t-e.mean;e.mean+=s/e.count;const i=t-e.mean;e.m2+=s*i}function R(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function N(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:Number.POSITIVE_INFINITY,max:e.count>0?e.max:Number.NEGATIVE_INFINITY}}function E(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function F(e,t,s){return"function"==typeof e?e(t,s):"string"==typeof e?E(t,e):void 0}function Y(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function X(e){const t=R(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:R(e.x),y:R(e.y),value:t}}var L=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const s=Y(F(this.config.binAccessor,e,t))??function(e){for(const t of T){const s=Y(E(e,t));if(s)return s}return"sediment"}(e),i=Y(F(this.config.labelAccessor,e,t))??s,n=function(e,t,s){if("number"==typeof e)return e;const i="function"==typeof e?e(t,s):"string"==typeof e?E(t,e):1,n="number"==typeof i?i:Number(i);return Number.isFinite(n)?n:1}(this.config.valueAccessor,e,t),o=Math.max(0,Math.floor(this.config.retainBodyIds??12));let r=this.bins.get(s);return r||(r={id:s,label:i,bodyIds:[],x:A(),y:A(),value:A()},this.bins.set(s,r)),r.label=i,r.lastBodyId=e.id,r.lastDatum=e.datum,D(r.x,e.x),D(r.y,e.y),D(r.value,n),o>0&&(r.bodyIds.push(e.id),r.bodyIds.length>o&&(r.bodyIds=r.bodyIds.slice(r.bodyIds.length-o))),X(r)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(X)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:N(t.x),y:N(t.y),value:N(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function K(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function H(e){const t=Math.max(0,Math.floor(e.liveBodies)),s=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+s,n=K(e.bodyLimit),o=K(e.engineMaxBodiesHint),r=function(e,t,s){if(!1===s)return;const i=K(s?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(n,o,e.options),a=null==n?0:Math.max(0,t-n),d=a>0?"overflow":null!=r&&i>=r?"warning":"ok";return{action:"overflow"!==d?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:o,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:s,state:d,warnAt:r}}var W={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},j={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function V(e={},t=j){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function $(e){return{...e,shape:{...e.shape},...e.fixedPosition?{fixedPosition:{...e.fixedPosition}}:{},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function z(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function G(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function _(e,t={}){const s=z(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,s)=>function(e,t,s){return"function"==typeof s?z(s(e,t)):"string"==typeof s?z(G(e,s)):z(e.spawnAt)??z(G(e,"arrivalTime"))??z(G(e,"timestamp"))??z(G(e,"time"))??z(G(e,"eventTime"))}(e,s,t.timeAccessor)),n=i.filter(e=>null!=e),o=n.length>0?Math.min(...n):0,r=z(t.timeScale)??1,a=r>0?r:1;return e.map((e,t)=>{const n=i[t],r=null==n?0:Math.max(0,n-o);return{...$(e),spawnAt:s+r/a}})}if("object"==typeof i){const t=z(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...$(e),spawnAt:s+i/t}))}return e.map(e=>({...$(e),spawnAt:s}))}function U(e){return{...$(e),sequence:e.sequence,spawnAt:e.spawnAt}}function Q(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function J(e){return!1!==e&&{...e}}function Z(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function ee(e){return{...e,gravity:{...e.gravity}}}function te(e,t,s,i){if("circle"===e.shape.type){const n=e.x-t,o=e.y-s,r=e.shape.radius+i,a=n*n+o*o;return a<=r*r?a:null}const n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),o=Math.max(Math.abs(s-e.y)-e.shape.height/2,0),r=n*n+o*o;return r<=i*i?r:null}function se(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}var ie={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function ne(e,t){const s={...e};for(const e of t){s[ie[e]]++}return s}function oe(e,t,s){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:ne(s,i)}}var re=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=oe({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const s=oe(e,t,this.revisions);this.revisions=s.revisions,this.latest=s;for(const e of[...this.listeners])e();return s}};import{quadtree as ae}from"d3-quadtree";var de=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,s,i,n,o=0,r){const a=this.ensure(e,t);if(!a)return null;let d=null,h=Number.POSITIVE_INFINITY;const c=Math.max(0,r?.searchRadius??Math.max(0,o)+this.maxSearchRadius),l=i-c,u=i+c,p=n-c,v=n+c;return a.visit((e,t,a,c,y)=>{if(c<l||t>u||y<p||a>v)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e&&(!r?.include||r.include(e))){const t=r?.distanceSquared?r.distanceSquared(e,i,n):te(e,i,n,Math.max(0,o));null!=t&&(t<h||t===h&&s.indexOf(e.id)>s.indexOf(d?.id??""))&&(d=e,h=t)}f=f.next}return!1}),d}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const s=e.readState();return 0===s.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=s.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=ae().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};var he=["data","scene-geometry","data-paint","accessibility","evidence"],ce=["scene-geometry","data-paint","accessibility","evidence"],le=["overlay","accessibility","evidence"],ue=(e,t)=>({retainedData:e,invalidations:t}),pe=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],ve=["scene-geometry","data-paint","accessibility","evidence"],ye=[],fe={engine:ue("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:ue("preserve",ve),colliders:ue("preserve",ve),sediment:ue("preserve",ve),bodyBudget:ue("preserve",pe),bodyLimit:ue("preserve",pe),eviction:ue("preserve",pe),fixedDt:ue("preserve",ye),maxDeltaSeconds:ue("preserve",ye),maxSubsteps:ue("preserve",ye),settleStepLimit:ue("preserve",ye),timeScale:ue("preserve",ye),observation:ue("preserve",ye)},me=ue("preserve",pe);function xe(e){let t="preserve";const s=new Set;for(const i of e){const e=fe[i]??me;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)s.add(t)}return{retainedData:t,invalidations:s}}var be=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function ge(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&be.every(s=>e[s]===t[s]))}function Se(e,t,s,i){return e||!t?"paused":s||!i?"running":"settled"}function we(e,t,s,i,n,o){const r={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===s)return r;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return r;const d=n.length-a;if(d<=0)return r;const h=function(e,t,s){if("sleeping-first"!==t)return s.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],o=[];for(const e of s)i.get(e)?n.push(e):o.push(e);return[...n,...o]}(e,s,n),c=h.slice(0,d);if(0===c.length)return r;const l=function(e,t,s,i){const n=new Map(e.readState().map(e=>[e.id,e])),o=[];for(const e of s){const s=n.get(e);if(!s)continue;const r=t.add(s);r&&(o.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:s.datum,x:s.x,y:s.y,binId:r.id,count:r.count,total:r.total}))}return o}(e,t,c,o);e.remove(c);const u=new Set(c);return{evicted:c,sedimented:l,liveBodyOrder:n.filter(e=>!u.has(e))}}var Ie=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,s){if(s>0)return void(this.seconds=0);const i=e.readState(this.scratch),n=this.speed*this.speed;let o=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=n){o=!1;break}this.seconds=o?this.seconds+Math.max(0,t):0}};function Be(e,t,s,i={}){let n,o=0;for(;o<t&&!i.shouldStop?.()&&(!1===i.stopAtRest||e.queueSize()>0||!e.atRest()||i.continueWhile?.());){e.step(e.fixedDt),e.advanceTime(e.fixedDt);const t=e.drainEvents();s.events&&(s.events.push(...t),e.observeKernelEvents(t,s.observations),e.observeSensorTransitions(s.observations));const r=[];if(e.spawnDue(r,s.observations),r.length>0){s.spawned.push(...r),n=e.observeBodyBudget(s.observations);const t=e.evictOverflow(s.observations);s.evicted?.push(...t.evicted),s.sedimented?.push(...t.sedimented)}o+=1,e.refreshQuiescence(e.fixedDt,r.length),i.afterStep?.()}return{steps:o,budget:n}}var Me=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new de,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new re,this.simulationState="settled",this.visible=!0,this.quiescence=new Ie;const{bodyBudget:t,colliders:s,engine:i,kernel:n,observation:o,sediment:r,...a}=e;this.config={...W,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=V(o),this.sediment=new L(r??!1),this.world=C(i,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),s&&this.world.setColliders(Q(s))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(s=>"kernel"===s?!ge(e.kernel,t.kernel):e[s]!==t[s])}(e,this.configInput),{colliders:s,bodyBudget:i,engine:n,kernel:o,observation:r,sediment:a,...d}=e;if(this.config={...this.config,...d},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=C(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!ge(o,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...o,gravity:{...e.options.gravity,...o.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}r&&(this.observation=V(r,this.observation)),this.sediment.updateConfig(a),s&&(this.world.setColliders(Q(s)),this.revision+=1),this.configInput={...this.configInput,...e};const h=xe(t);this.updateResults.record({kind:"config",keys:t},h.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(Q(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},xe(["colliders"]).invalidations)}enqueue(e,t){const s=Array.isArray(e)?e:[e],i=t?_(s,{...t,startAt:t.startAt??this.elapsedSeconds}):s;for(const e of i)this.queue.push({...$(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(Z),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?he:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne($(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},he)}materializeDueSpawns(){const e=this.revision,t=[],s=[];return this.spawnDue(t,s),0===t.length||(this.observeBodyBudget(s),this.evictOverflow(s),this.syncSimulationState(s),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?he:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},he)}tick(e,t){const s=this.revision,i=[],n=[],o=[],r=[],a=[];if(this.paused||!this.visible){const e=this.result(0,i,n,o,r,a,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const d=Math.max(0,Math.min(Number.isFinite(e)?e:0,this.config.maxDeltaSeconds))*this.config.timeScale;this.spawnDue(i,a);const h=this.observeBodyBudget(a),c=this.evictOverflow(a);n.push(...c.evicted),o.push(...c.sedimented),this.syncSimulationState(a),i.length>0&&this.quiescence.reset(),this.accumulator+=d;const l=this.stepObserver(t,{spawned:i,evicted:n,sedimented:o,events:r,observations:a}),u=d>0?Math.floor((this.accumulator+1e-9*this.config.fixedDt)/this.config.fixedDt):0,{steps:p,budget:v}=Be(this.settleHost(),Math.min(u,this.config.maxSubsteps),{spawned:i,evicted:n,sedimented:o,events:r,observations:a},{stopAtRest:!1,shouldStop:()=>this.paused||!this.visible,afterStep:l});this.accumulator=Math.max(0,this.accumulator-p*this.config.fixedDt),p===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),(p>0||i.length>0||n.length>0||o.length>0||r.length>0)&&(this.revision+=1);const y=this.result(p,i,n,o,r,a,void 0,v??h);return this.updateResults.record({kind:"tick",count:p},this.revision!==s?i.length||n.length||o.length?he:ce:[]),y}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit,t){return this.runSettle(e,!0,t)}stepObserver(e,t){return function(e,t){if(!e)return;const s=["spawned","evicted","sedimented","events","observations"],i={spawned:0,evicted:0,sedimented:0,events:0,observations:0},n=n=>{const o=t(n),r={...o,spawned:o.spawned.slice(i.spawned),evicted:o.evicted.slice(i.evicted),sedimented:o.sedimented.slice(i.sedimented),events:o.events.slice(i.events),observations:o.observations.slice(i.observations)};for(const e of s)i[e]=o[e].length;e.onStep(r)};return n(0),()=>n(1)}(e,e=>(e&&(this.revision+=1),this.result(e,t.spawned,t.evicted,t.sedimented,t.events,t.observations)))}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t,s){const i=this.revision,n=[],o=[],r=[],a=[],d=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,n,o,r,a,d??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,d);const h=this.observeBodyBudget(d),c=this.evictOverflow(d);o.push(...c.evicted),r.push(...c.sedimented),this.syncSimulationState(d),n.length>0&&this.quiescence.reset();const l=t?{spawned:n,evicted:o,sedimented:r,events:a,observations:d}:{spawned:n},u=this.stepObserver(s,{spawned:n,evicted:o,sedimented:r,events:a,observations:d??[]}),{steps:p,budget:v}=Be(this.settleHost(),e,l,{afterStep:u,continueWhile:s?.continueWhile,shouldStop:t?()=>this.paused||!this.visible:void 0}),y=n.length+o.length+r.length>0;(p>0||y||a.length>0)&&(this.revision+=1);const f=this.result(p,n,o,r,a,d??[],void 0,v??h);return this.updateResults.record({kind:"settle",count:p},this.revision===i?[]:y?he:ce),f}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return function(e,t={}){const{baselineY:s=0,binWidth:i=24,gap:n=2,maxHeight:o=80,value:r="count",x:a}=t,d=Math.max(1,...e.map(e=>e[r]));return e.map((e,t)=>{const h=Math.max(0,e[r]/d*o),c=a?.(e,t)??t*(i+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:c,y:s-h,width:i,height:h,meanX:e.x.mean,meanY:e.y.mean}})}(this.readSediment(),e)}hitTest(e,t,s=0,i){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,s,i)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:s,chartId:i,...n}=e,o={...n,timestamp:t??this.elapsedSeconds,chartType:s??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(o),this.updateResults.record({kind:"update",count:1},["evidence"]),o}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?le:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?le:[])}remove(e){const t=new Set(e),s=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const n=e.filter(e=>s.has(e)||i.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?he:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},ce),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},ce)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},ce)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,s,i)=>e.applyImpulse(t,s,i),clear:()=>e.clear(),hitTest:(t,s,i)=>e.hitTest(t,s,i),pause:()=>e.setPaused(!0),push:(t,s)=>e.enqueue(t,s),pushMany:(t,s)=>e.enqueue(t,s),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:J(this.bodyBudget),config:{...this.config,kernel:ee(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(U),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){const t=this.simulationState;this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:J(e.bodyBudget??{}),kernel:ee(e.world.options)},this.bodyBudget=J(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(U).sort(Z),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??Se(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},he),this.simulationState!==t&&this.observation.onSimulationStateChange?.(this.simulationState,t)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds+1e-9*this.config.fixedDt;){const s=this.queue.shift();if(!s)return;this.spawnOne(s,t),e.push(s.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const s=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:s?.datum??e.datum,x:s?.x??e.x,y:s?.y??e.y},t)}result(e,t,s,i,n,o,r,a=this.evaluateBodyBudget()){this.syncSimulationState(o);const d=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:s,events:n,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:r??(!this.paused&&this.visible&&(this.queue.length>0||!this.atRest())),sleeping:d,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,s){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);s.emit({type:"physics-settle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,s){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const n=new Map(e.readState().map(e=>[e.id,e])),o=(e,t)=>{const{sensorId:i,bodyId:o}=se(t),r=s.observation.sensors[i],a=n.get(o);s.emit({type:"enter"===e?r?.enterType??"physics-bin-enter":r?.exitType??"physics-bin-exit",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:o,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:r?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||o("enter",e);for(const e of Array.from(t).sort())i.has(e)||o("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const s of e)t.has(se(s).bodyId)&&e.delete(s)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return H({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const s=`${t.state}:${t.action}`;return s===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=s,function(e,t){t.emit({type:"overflow"===e.state?"physics-budget-overflow":"physics-budget-warning",timestamp:t.elapsedSeconds,chartType:t.observation.chartType,chartId:t.observation.chartId,budgetAction:e.action,bodyLimit:e.bodyLimit,engineMaxBodiesHint:e.engineMaxBodiesHint,liveBodies:e.liveBodies,overflow:e.overflow,projectedBodies:e.projectedBodies,queuedBodies:e.queuedBodies,warnAt:e.warnAt})}(t,this.observationContext(e))),t}syncSimulationState(e){const t=Se(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const s=this.simulationState;this.simulationState=t,function(e,t,s){s.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||s.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,simulationState:t,previousSimulationState:e})}(s,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:s,liveBodyOrder:i}=we(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:s}}};function Oe(e,t){return function(e,t,s=[],i){const n=new Array(t.length),o=new Float32Array(2*t.length),r=new Float32Array(2*t.length),a=new Uint8Array(t.length);return t.forEach((e,t)=>{const s=2*t;n[t]=e.id,o[s]=e.x,o[s+1]=e.y,r[s]=e.vx,r[s+1]=e.vy,a[t]=e.sleeping?1:0}),{bodies:t,ids:n,positions:o,result:e,sediment:s,sleeping:a,snapshot:i,velocities:r}}(t,e.readBodies(),e.readSediment(),e.snapshot())}function qe(e){return Oe(e,e.tick(0))}var ke=function(){let e=new Me;return{handle(t){switch(t.type){case"init":return e=new Me(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:qe(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:qe(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:qe(e)};case"tick":return{type:"frame",frame:Oe(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:Oe(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:qe(e)};case"clear":return e.clear(),{type:"frame",frame:qe(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:qe(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:qe(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:qe(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:qe(e)}}}}}();function Pe(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:{message:String(e)}}self.onmessage=e=>{const t=e.data;try{const e=ke.handle(t.command);self.postMessage({ok:!0,payload:e,requestId:t.requestId},function(e){return"frame"===e.type||"removed"===e.type?[(t=e.frame).positions.buffer,t.velocities.buffer,t.sleeping.buffer]:[];var t}(e))}catch(e){self.postMessage({error:Pe(e),ok:!1,requestId:t.requestId})}};
|
|
1
|
+
function e(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}function t(e){const t=e.fixedPosition;Number.isFinite(t?.x)&&(e.x=e.prevX=t.x,e.vx=0),Number.isFinite(t?.y)&&(e.y=e.prevY=t.y,e.vy=0)}function s(e){if(!e)return;const t=Number.isFinite(e.x)?e.x:void 0,s=Number.isFinite(e.y)?e.y:void 0;return null==t&&null==s?void 0:{x:t,y:s}}function i(e,t,s){const i="x"===s?"y":"x",n=Math.abs(t[s]-e[s]),o=t[i]-e[i],r=(e,t)=>"circle"===e.shape.type?e.shape.radius:("x"===t?e.shape.width:e.shape.height)/2;let a;if("circle"===e.shape.type&&"circle"===t.shape.type){const s=e.shape.radius+t.shape.radius;a=Math.sqrt(Math.max(0,s*s-n*n))}else if("aabb"===e.shape.type&&"aabb"===t.shape.type)a=r(e,i)+r(t,i);else{const o="circle"===e.shape.type?e:t,d="aabb"===e.shape.type?e:t,h=r(o,s),c=Math.max(0,n-r(d,s));a=r(d,i)+Math.sqrt(Math.max(0,h*h-c*c))}const d=o<0?-1:1;return{nx:"x"===i?d:0,ny:"y"===i?d:0,penetration:Math.max(0,a-Math.abs(o))}}function n(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function o(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function r(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,...e.fixedPosition?{fixedPosition:s(e.fixedPosition)}:{},shape:n(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function a(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function d(e){return{id:e.id,shape:o(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:a(e.bodyFilter),index:e.index}}var h={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},c=1e-9,l=.005;function u(e,t,s){return Math.max(t,Math.min(s,e))}function p(e,t,s){return Math.min(e??s,t??s)}function v(e,t,s){return u(Math.max(e??s,t??s),0,1)}function y(e){return e<0?-1:1}function f(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,s=e.shape.height/2;return{minX:e.x-t,minY:e.y-s,maxX:e.x+t,maxY:e.y+s}}function m(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,s=t.height/2;return{minX:t.x-e,minY:t.y-s,maxX:t.x+e,maxY:t.y+s}}const s=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-s,minY:Math.min(t.y1,t.y2)-s,maxX:Math.max(t.x1,t.x2)+s,maxY:Math.max(t.y1,t.y2)+s}}function x(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function b(e,t,s,i,n,o,r,a){const d=n-e,h=(s+r)/2-Math.abs(d);if(h<=0)return null;const c=o-t,l=(i+a)/2-Math.abs(c);return l<=0?null:h<l?{nx:y(d),ny:0,penetration:h}:{nx:0,ny:y(c),penetration:l}}function g(e,t,s,i,n,o,r){const a=o/2,d=r/2,h=e-u(e,i-a,i+a),l=t-u(t,n-d,n+d),p=h*h+l*l;if(p>s*s)return null;if(p<=c){const o=Math.abs(e-(i-a)),r=Math.abs(e-(i+a)),h=Math.abs(t-(n-d)),c=Math.abs(t-(n+d)),l=Math.min(o,r,h,c);return l===o?{nx:-1,ny:0,penetration:s+o}:l===r?{nx:1,ny:0,penetration:s+r}:l===h?{nx:0,ny:-1,penetration:s+h}:{nx:0,ny:1,penetration:s+c}}const v=Math.sqrt(p);return{nx:h/v,ny:l/v,penetration:s-v}}function S(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,s,i,n,o){const r=i-e,a=n-t,d=s+o,h=r*r+a*a;if(h>=d*d)return null;if(h<=c)return{nx:1,ny:0,penetration:d};const l=Math.sqrt(h);return{nx:r/l,ny:a/l,penetration:d-l}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return b(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const s=g(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return s?{nx:-s.nx,ny:-s.ny,penetration:s.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?g(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function w(e,t){const s=t.shape;if("aabb"===s.type)return"circle"===e.shape.type?g(e.x,e.y,e.shape.radius,s.x,s.y,s.width,s.height):b(s.x,s.y,s.width,s.height,e.x,e.y,e.shape.width,e.shape.height);const i="circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2;return function(e,t,s,i,n,o,r,a=0){const d=o-i,h=r-n,l=d*d+h*h,p=l<=c?0:u(((e-i)*d+(t-n)*h)/l,0,1),v=s+a/2,y=e-(i+d*p),f=t-(n+h*p),m=y*y+f*f;if(m>=v*v)return null;if(m<=c){const e=Math.sqrt(l);return e<=c?{nx:1,ny:0,penetration:v}:{nx:-h/e,ny:d/e,penetration:v}}const x=Math.sqrt(m);return{nx:y/x,ny:f/x,penetration:v-x}}(e.x,e.y,i,s.x1,s.y1,s.x2,s.y2,s.thickness??0)}function I(e,t){return`${e}\0${t}`}function B(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function M(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function O(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const s=function(e,t){if(!t)return;let s=e;for(const e of t.split(".")){if(null==s||"object"!=typeof s)return;if(!Object.prototype.hasOwnProperty.call(s,e))return;s=s[e]}return s}(e,t.property);return!("equals"in t&&!Object.is(s,t.equals))&&((!("notEquals"in t)||!Object.is(s,t.notEquals))&&(!(t.oneOf&&!M(s,t.oneOf))&&(!t.notOneOf||!M(s,t.notOneOf))))}function q(e,t){return O(t,e.bodyFilter)}var k=class{constructor(t={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...h,...t},this.random=e(this.options.seed)}init(t={}){this.options={...h,...t},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const i={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(c,e.mass??1),bodyCollisions:e.bodyCollisions??!0,...e.fixedPosition?{fixedPosition:s(e.fixedPosition)}:{},shape:n(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};t(i),this.nextBodyIndex+=1,this.bodies.set(e.id,i)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))B(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:o(t.shape),bodyFilter:a(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??`spring-${this.nextSpringIndex}`;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,s,i){const n=this.bodies.get(e);n&&(n.vx+=s/n.mass,n.vy+=i/n.mass,t(n),this.wake(n))}step(e=this.options.fixedDt){const s=Math.max(0,e);if(this.lastEvents=[],0===s)return;const i=this.sortedBodies();for(const e of i)e.prevX=e.x,e.prevY=e.y;this.applySprings(s);const n=this.options.maxVelocity;for(const e of i)if(!e.sleeping){if(e.vx+=this.options.gravity.x*s,e.vy+=this.options.gravity.y*s,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,t(e),n>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>n){const s=n/t;e.vx*=s,e.vy*=s}}e.x+=e.vx*s,e.y+=e.vy*s}this.supportedThisStep.clear();const o=this.bodyPairKeys(i),r=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;e<this.options.collisionIterations;e+=1)this.resolveBodyPairs(i,o,0===e),this.resolveColliders(i,r,0===e);this.updateSensors(i),this.updateSleeping(i,s)}settle(e=1200,t=this.options.fixedDt){let s=0;for(;s<e&&!this.allSleeping();)this.step(t),s+=1;return s}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,...t.fixedPosition?{fixedPosition:s(t.fixedPosition)}:{},shape:n(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(B)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(r),colliders:this.sortedColliders().map(d),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(s){this.options={...s.options,gravity:{...s.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(s.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of s.bodies){const s=r(e);t(s),this.bodies.set(s.id,s),this.nextBodyIndex=Math.max(this.nextBodyIndex,s.index+1)}this.nextColliderIndex=0;for(const e of s.colliders){const t=d(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of s.springs){this.springs.set(e.id,{...e,target:{...e.target}});const t=/^spring-(\d+)$/.exec(e.id);t&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(t[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const s=this.bodies.get(t.bodyId);if(!s||s.sleeping)continue;const i="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!i)continue;const n=i.x-s.x,o=i.y-s.y,r=n*n+o*o,a=Math.sqrt(r);if(a<=c)continue;const d=n/a,h=o/a,l="vx"in i?i.vx:0,u="vy"in i?i.vy:0,p=(l-s.vx)*d+(u-s.vy)*h,v=(a-t.restLength)*t.stiffness+p*t.damping;s.vx+=v*d*e/s.mass,s.vy+=v*h*e/s.mass}}resolveBodyPairs(e,t,s){for(const i of t){const[t,n]=i.split(":").map(Number),o=e[t],r=e[n];if(!o||!r)continue;const a=S(o,r);a&&(this.resolveDynamicCollision(o,r,a),s&&this.lastEvents.push({type:"contact",bodyId:o.id,otherId:r.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),s=new Map;for(let i=0;i<e.length;i+=1){if(!1===e[i].bodyCollisions)continue;const n=f(e[i]),o=Math.floor(n.minX/t),r=Math.floor(n.maxX/t),a=Math.floor(n.minY/t),d=Math.floor(n.maxY/t);for(let e=o;e<=r;e+=1)for(let t=a;t<=d;t+=1){const n=`${e}:${t}`,o=s.get(n);o?o.push(i):s.set(n,[i])}}const i=new Set;for(const t of Array.from(s.keys()).sort()){const n=s.get(t)??[];n.sort((e,t)=>e-t);for(let t=0;t<n.length;t+=1)for(let s=t+1;s<n.length;s+=1){const o=n[t],r=n[s];!1!==e[o].bodyCollisions&&!1!==e[r].bodyCollisions&&(x(f(e[o]),f(e[r]))&&i.add(`${o}:${r}`))}}return Array.from(i).sort((e,t)=>{const[s,i]=e.split(":").map(Number),[n,o]=t.split(":").map(Number);return s===n?i-o:s-n})}resolveDynamicCollision(e,t,s){(e.fixedPosition||t.fixedPosition)&&(!e.sleeping&&null==e.fixedPosition?.x||!t.sleeping&&null==t.fixedPosition?.x?!e.sleeping&&null==e.fixedPosition?.y||!t.sleeping&&null==t.fixedPosition?.y||(s=i(e,t,"y")):s=i(e,t,"x")),e.sleeping&&this.contactOpposesGravity(s.nx,s.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-s.nx,-s.ny)&&this.supportedThisStep.add(e.id);const n=e.sleeping?0:1/e.mass,o=t.sleeping?0:1/t.mass,r=null==e.fixedPosition?.x?n:0,a=null==e.fixedPosition?.y?n:0,d=null==t.fixedPosition?.x?o:0,h=null==t.fixedPosition?.y?o:0,u=e.fixedPosition||t.fixedPosition?s.nx**2*(r+d)+s.ny**2*(a+h):n+o;if(u<=c)return;const v=Math.max(0,s.penetration-l)/u;e.x-=s.nx*v*r,e.y-=s.ny*v*a,t.x+=s.nx*v*d,t.y+=s.ny*v*h;const y=t.vx-e.vx,f=t.vy-e.vy,m=y*s.nx+f*s.ny;if(m>0)return;const x=Math.abs(m),b=-(1+p(e.restitution,t.restitution,this.options.restitution))*m/u,g=b*s.nx,S=b*s.ny;e.vx-=g*r,e.vy-=S*a,t.vx+=g*d,t.vy+=S*h,this.applyFriction(e,t,s,b,n,o),x>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,s,i,n,o){const r=-s.ny,a=s.nx,d=(t.vx-e.vx)*r+(t.vy-e.vy)*a,h=null==e.fixedPosition?.x?n:0,l=null==e.fixedPosition?.y?n:0,p=null==t.fixedPosition?.x?o:0,y=null==t.fixedPosition?.y?o:0,f=e.fixedPosition||t.fixedPosition?r**2*(h+p)+a**2*(l+y):n+o;if(Math.abs(d)<=c||f<=c)return;const m=v(e.friction,t.friction,this.options.friction),x=u(-d/f,-i*m,i*m),b=x*r,g=x*a;e.vx-=b*h,e.vy-=g*l,t.vx+=b*p,t.vy+=g*y}resolveColliders(e,t,s){for(const i of e)for(const e of t){if(!q(e,i))continue;if(!x(f(i),m(e)))continue;const t=w(i,e);t&&(this.resolveStaticCollision(i,e,t),this.contactOpposesGravity(t.nx,t.ny)&&this.supportedThisStep.add(i.id),s&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,s,i){e.x+=i.nx*Math.max(0,i.penetration-l),e.y+=i.ny*Math.max(0,i.penetration-l);const n=e.vx*i.nx+e.vy*i.ny;if(n<0){const t=p(e.restitution,s.restitution,this.options.restitution);e.vx-=(1+t)*n*i.nx,e.vy-=(1+t)*n*i.ny;const o=-i.ny,r=i.nx,a=e.vx*o+e.vy*r,d=v(e.friction,s.friction,this.options.friction);e.vx-=a*o*d,e.vy-=a*r*d}t(e)}updateSensors(e){const t=new Set,s=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=f(i);for(const n of s){if(!q(n,i))continue;if(!x(e,m(n)))continue;if(!w(i,n))continue;const s=I(n.id,i.id);t.add(s),this.activeSensors.has(s)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:n.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:s,bodyId:i}=B(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:s})}this.activeSensors=t}updateSleeping(e,t){const s=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e){const e=Math.sqrt(i.vx*i.vx+i.vy*i.vy),n=Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY));!(e<this.options.sleepSpeed&&n<this.options.sleepSpeed*t)||s&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,!i.sleeping&&i.sleepTime>=this.options.sleepAfter&&(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}}contactOpposesGravity(e,t){const{x:s,y:i}=this.options.gravity,n=Math.hypot(s,i);return n<=1e-9||(e*s+t*i)/n<-.2}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},P=class{constructor(e={}){this.id="builtin",this.capabilities={...(new k).capabilities,engine:"builtin"},this.world=new k(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function C(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new P(e)}(t)}var T=["binId","targetBin","category","windowIndex","lane","group"];function A(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function D(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const s=t-e.mean;e.mean+=s/e.count;const i=t-e.mean;e.m2+=s*i}function R(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function N(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:Number.POSITIVE_INFINITY,max:e.count>0?e.max:Number.NEGATIVE_INFINITY}}function E(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function F(e,t,s){return"function"==typeof e?e(t,s):"string"==typeof e?E(t,e):void 0}function Y(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function X(e){const t=R(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:R(e.x),y:R(e.y),value:t}}var L=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const s=Y(F(this.config.binAccessor,e,t))??function(e){for(const t of T){const s=Y(E(e,t));if(s)return s}return"sediment"}(e),i=Y(F(this.config.labelAccessor,e,t))??s,n=function(e,t,s){if("number"==typeof e)return e;const i="function"==typeof e?e(t,s):"string"==typeof e?E(t,e):1,n="number"==typeof i?i:Number(i);return Number.isFinite(n)?n:1}(this.config.valueAccessor,e,t),o=Math.max(0,Math.floor(this.config.retainBodyIds??12));let r=this.bins.get(s);return r||(r={id:s,label:i,bodyIds:[],x:A(),y:A(),value:A()},this.bins.set(s,r)),r.label=i,r.lastBodyId=e.id,r.lastDatum=e.datum,D(r.x,e.x),D(r.y,e.y),D(r.value,n),o>0&&(r.bodyIds.push(e.id),r.bodyIds.length>o&&(r.bodyIds=r.bodyIds.slice(r.bodyIds.length-o))),X(r)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(X)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:N(t.x),y:N(t.y),value:N(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function K(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function H(e){const t=Math.max(0,Math.floor(e.liveBodies)),s=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+s,n=K(e.bodyLimit),o=K(e.engineMaxBodiesHint),r=function(e,t,s){if(!1===s)return;const i=K(s?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(n,o,e.options),a=null==n?0:Math.max(0,t-n),d=a>0?"overflow":null!=r&&i>=r?"warning":"ok";return{action:"overflow"!==d?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:o,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:s,state:d,warnAt:r}}var W={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},j={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function V(e={},t=j){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function $(e){return{...e,shape:{...e.shape},...e.fixedPosition?{fixedPosition:{...e.fixedPosition}}:{},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function z(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function G(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function _(e,t={}){const s=z(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){let i=1/0;const n=e.map((e,s)=>{const n=function(e,t,s){return"function"==typeof s?z(s(e,t)):"string"==typeof s?z(G(e,s)):z(e.spawnAt)??z(G(e,"arrivalTime"))??z(G(e,"timestamp"))??z(G(e,"time"))??z(G(e,"eventTime"))}(e,s,t.timeAccessor);return null!=n&&(i=Math.min(i,n)),n}),o=z(t.timeScale)??1,r=o>0?o:1;return e.map((e,t)=>{const o=n[t],a=null==o?0:Math.max(0,o-i);return{...$(e),spawnAt:s+a/r}})}if("object"==typeof i){const t=z(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...$(e),spawnAt:s+i/t}))}return e.map(e=>({...$(e),spawnAt:s}))}function U(e){return{...$(e),sequence:e.sequence,spawnAt:e.spawnAt}}function Q(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function J(e){return!1!==e&&{...e}}function Z(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function ee(e){return{...e,gravity:{...e.gravity}}}function te(e,t,s,i){if("circle"===e.shape.type){const n=e.x-t,o=e.y-s,r=e.shape.radius+i,a=n*n+o*o;return a<=r*r?a:null}const n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),o=Math.max(Math.abs(s-e.y)-e.shape.height/2,0),r=n*n+o*o;return r<=i*i?r:null}function se(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}var ie={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function ne(e,t){const s={...e};for(const e of t){s[ie[e]]++}return s}function oe(e,t,s){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:ne(s,i)}}var re=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=oe({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const s=oe(e,t,this.revisions);this.revisions=s.revisions,this.latest=s;for(const e of[...this.listeners])e();return s}};import{quadtree as ae}from"d3-quadtree";var de=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,s,i,n,o=0,r){const a=this.ensure(e,t);if(!a)return null;let d=null,h=Number.POSITIVE_INFINITY;const c=Math.max(0,r?.searchRadius??Math.max(0,o)+this.maxSearchRadius),l=i-c,u=i+c,p=n-c,v=n+c;return a.visit((e,t,a,c,y)=>{if(c<l||t>u||y<p||a>v)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e&&(!r?.include||r.include(e))){const t=r?.distanceSquared?r.distanceSquared(e,i,n):te(e,i,n,Math.max(0,o));null!=t&&(t<h||t===h&&s.indexOf(e.id)>s.indexOf(d?.id??""))&&(d=e,h=t)}f=f.next}return!1}),d}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const s=e.readState();return 0===s.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=s.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=ae().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};var he=["data","scene-geometry","data-paint","accessibility","evidence"],ce=["scene-geometry","data-paint","accessibility","evidence"],le=["overlay","accessibility","evidence"],ue=(e,t)=>({retainedData:e,invalidations:t}),pe=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],ve=["scene-geometry","data-paint","accessibility","evidence"],ye=[],fe={engine:ue("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:ue("preserve",ve),colliders:ue("preserve",ve),sediment:ue("preserve",ve),bodyBudget:ue("preserve",pe),bodyLimit:ue("preserve",pe),eviction:ue("preserve",pe),fixedDt:ue("preserve",ye),maxDeltaSeconds:ue("preserve",ye),maxSubsteps:ue("preserve",ye),settleStepLimit:ue("preserve",ye),timeScale:ue("preserve",ye),observation:ue("preserve",ye)},me=ue("preserve",pe);function xe(e){let t="preserve";const s=new Set;for(const i of e){const e=fe[i]??me;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)s.add(t)}return{retainedData:t,invalidations:s}}var be=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function ge(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&be.every(s=>e[s]===t[s]))}function Se(e,t,s,i){return e||!t?"paused":s||!i?"running":"settled"}function we(e,t,s,i,n,o){const r={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===s)return r;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return r;const d=n.length-a;if(d<=0)return r;const h=function(e,t,s){if("sleeping-first"!==t)return s.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],o=[];for(const e of s)i.get(e)?n.push(e):o.push(e);return[...n,...o]}(e,s,n),c=h.slice(0,d);if(0===c.length)return r;const l=function(e,t,s,i){const n=new Map(e.readState().map(e=>[e.id,e])),o=[];for(const e of s){const s=n.get(e);if(!s)continue;const r=t.add(s);r&&(o.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:s.datum,x:s.x,y:s.y,binId:r.id,count:r.count,total:r.total}))}return o}(e,t,c,o);e.remove(c);const u=new Set(c);return{evicted:c,sedimented:l,liveBodyOrder:n.filter(e=>!u.has(e))}}var Ie=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,s){if(s>0)return void(this.seconds=0);const i=e.readState(this.scratch),n=this.speed*this.speed;let o=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=n){o=!1;break}this.seconds=o?this.seconds+Math.max(0,t):0}};function Be(e,t,s,i={}){let n,o=0;for(;o<t&&!i.shouldStop?.()&&(!1===i.stopAtRest||e.queueSize()>0||!e.atRest()||i.continueWhile?.());){e.step(e.fixedDt),e.advanceTime(e.fixedDt);const t=e.drainEvents();s.events&&(s.events.push(...t),e.observeKernelEvents(t,s.observations),e.observeSensorTransitions(s.observations));const r=[];if(e.spawnDue(r,s.observations),r.length>0){s.spawned.push(...r),n=e.observeBodyBudget(s.observations);const t=e.evictOverflow(s.observations);s.evicted?.push(...t.evicted),s.sedimented?.push(...t.sedimented)}o+=1,e.refreshQuiescence(e.fixedDt,r.length),i.afterStep?.()}return{steps:o,budget:n}}var Me=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new de,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new re,this.simulationState="settled",this.visible=!0,this.quiescence=new Ie;const{bodyBudget:t,colliders:s,engine:i,kernel:n,observation:o,sediment:r,...a}=e;this.config={...W,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=V(o),this.sediment=new L(r??!1),this.world=C(i,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),s&&this.world.setColliders(Q(s))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(s=>"kernel"===s?!ge(e.kernel,t.kernel):e[s]!==t[s])}(e,this.configInput),{colliders:s,bodyBudget:i,engine:n,kernel:o,observation:r,sediment:a,...d}=e;if(this.config={...this.config,...d},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=C(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!ge(o,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...o,gravity:{...e.options.gravity,...o.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}r&&(this.observation=V(r,this.observation)),this.sediment.updateConfig(a),s&&(this.world.setColliders(Q(s)),this.revision+=1),this.configInput={...this.configInput,...e};const h=xe(t);this.updateResults.record({kind:"config",keys:t},h.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(Q(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},xe(["colliders"]).invalidations)}enqueue(e,t){const s=Array.isArray(e)?e:[e],i=t?_(s,{...t,startAt:t.startAt??this.elapsedSeconds}):s;for(const e of i)this.queue.push({...$(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(Z),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?he:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne($(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},he)}materializeDueSpawns(){const e=this.revision,t=[],s=[];return this.spawnDue(t,s),0===t.length||(this.observeBodyBudget(s),this.evictOverflow(s),this.syncSimulationState(s),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?he:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},he)}tick(e,t){const s=this.revision,i=[],n=[],o=[],r=[],a=[];if(this.paused||!this.visible){const e=this.result(0,i,n,o,r,a,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const d=Math.max(0,Math.min(Number.isFinite(e)?e:0,this.config.maxDeltaSeconds))*this.config.timeScale;this.spawnDue(i,a);const h=this.observeBodyBudget(a),c=this.evictOverflow(a);n.push(...c.evicted),o.push(...c.sedimented),this.syncSimulationState(a),i.length>0&&this.quiescence.reset(),this.accumulator+=d;const l=this.stepObserver(t,{spawned:i,evicted:n,sedimented:o,events:r,observations:a}),u=d>0?Math.floor((this.accumulator+1e-9*this.config.fixedDt)/this.config.fixedDt):0,{steps:p,budget:v}=Be(this.settleHost(),Math.min(u,this.config.maxSubsteps),{spawned:i,evicted:n,sedimented:o,events:r,observations:a},{stopAtRest:!1,shouldStop:()=>this.paused||!this.visible,afterStep:l});this.accumulator=Math.max(0,this.accumulator-p*this.config.fixedDt),p===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),(p>0||i.length>0||n.length>0||o.length>0||r.length>0)&&(this.revision+=1);const y=this.result(p,i,n,o,r,a,void 0,v??h);return this.updateResults.record({kind:"tick",count:p},this.revision!==s?i.length||n.length||o.length?he:ce:[]),y}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit,t){return this.runSettle(e,!0,t)}stepObserver(e,t){return function(e,t){if(!e)return;const s=["spawned","evicted","sedimented","events","observations"],i={spawned:0,evicted:0,sedimented:0,events:0,observations:0},n=n=>{const o=t(n),r={...o,spawned:o.spawned.slice(i.spawned),evicted:o.evicted.slice(i.evicted),sedimented:o.sedimented.slice(i.sedimented),events:o.events.slice(i.events),observations:o.observations.slice(i.observations)};for(const e of s)i[e]=o[e].length;e.onStep(r)};return n(0),()=>n(1)}(e,e=>(e&&(this.revision+=1),this.result(e,t.spawned,t.evicted,t.sedimented,t.events,t.observations)))}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t,s){const i=this.revision,n=[],o=[],r=[],a=[],d=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,n,o,r,a,d??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,d);const h=this.observeBodyBudget(d),c=this.evictOverflow(d);o.push(...c.evicted),r.push(...c.sedimented),this.syncSimulationState(d),n.length>0&&this.quiescence.reset();const l=t?{spawned:n,evicted:o,sedimented:r,events:a,observations:d}:{spawned:n},u=this.stepObserver(s,{spawned:n,evicted:o,sedimented:r,events:a,observations:d??[]}),{steps:p,budget:v}=Be(this.settleHost(),e,l,{afterStep:u,continueWhile:s?.continueWhile,shouldStop:t?()=>this.paused||!this.visible:void 0}),y=n.length+o.length+r.length>0;(p>0||y||a.length>0)&&(this.revision+=1);const f=this.result(p,n,o,r,a,d??[],void 0,v??h);return this.updateResults.record({kind:"settle",count:p},this.revision===i?[]:y?he:ce),f}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return function(e,t={}){const{baselineY:s=0,binWidth:i=24,gap:n=2,maxHeight:o=80,value:r="count",x:a}=t,d=e.reduce((e,t)=>Math.max(e,t[r]),1);return e.map((e,t)=>{const h=Math.max(0,e[r]/d*o),c=a?.(e,t)??t*(i+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:c,y:s-h,width:i,height:h,meanX:e.x.mean,meanY:e.y.mean}})}(this.readSediment(),e)}hitTest(e,t,s=0,i){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,s,i)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:s,chartId:i,...n}=e,o={...n,timestamp:t??this.elapsedSeconds,chartType:s??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(o),this.updateResults.record({kind:"update",count:1},["evidence"]),o}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?le:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?le:[])}remove(e){const t=new Set(e),s=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const n=e.filter(e=>s.has(e)||i.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?he:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},ce),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},ce)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},ce)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,s,i)=>e.applyImpulse(t,s,i),clear:()=>e.clear(),hitTest:(t,s,i)=>e.hitTest(t,s,i),pause:()=>e.setPaused(!0),push:(t,s)=>e.enqueue(t,s),pushMany:(t,s)=>e.enqueue(t,s),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:J(this.bodyBudget),config:{...this.config,kernel:ee(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(U),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){const t=this.simulationState;this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:J(e.bodyBudget??{}),kernel:ee(e.world.options)},this.bodyBudget=J(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(U).sort(Z),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??Se(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},he),this.simulationState!==t&&this.observation.onSimulationStateChange?.(this.simulationState,t)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds+1e-9*this.config.fixedDt;){const s=this.queue.shift();if(!s)return;this.spawnOne(s,t),e.push(s.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const s=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:s?.datum??e.datum,x:s?.x??e.x,y:s?.y??e.y},t)}result(e,t,s,i,n,o,r,a=this.evaluateBodyBudget()){this.syncSimulationState(o);const d=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:s,events:n,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:r??(!this.paused&&this.visible&&(this.queue.length>0||!this.atRest())),sleeping:d,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,s){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);s.emit({type:"physics-settle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,s){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const n=new Map(e.readState().map(e=>[e.id,e])),o=(e,t)=>{const{sensorId:i,bodyId:o}=se(t),r=s.observation.sensors[i],a=n.get(o);s.emit({type:"enter"===e?r?.enterType??"physics-bin-enter":r?.exitType??"physics-bin-exit",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:o,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:r?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||o("enter",e);for(const e of Array.from(t).sort())i.has(e)||o("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const s of e)t.has(se(s).bodyId)&&e.delete(s)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return H({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const s=`${t.state}:${t.action}`;return s===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=s,function(e,t){t.emit({type:"overflow"===e.state?"physics-budget-overflow":"physics-budget-warning",timestamp:t.elapsedSeconds,chartType:t.observation.chartType,chartId:t.observation.chartId,budgetAction:e.action,bodyLimit:e.bodyLimit,engineMaxBodiesHint:e.engineMaxBodiesHint,liveBodies:e.liveBodies,overflow:e.overflow,projectedBodies:e.projectedBodies,queuedBodies:e.queuedBodies,warnAt:e.warnAt})}(t,this.observationContext(e))),t}syncSimulationState(e){const t=Se(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const s=this.simulationState;this.simulationState=t,function(e,t,s){s.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||s.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,simulationState:t,previousSimulationState:e})}(s,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:s,liveBodyOrder:i}=we(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:s}}};function Oe(e,t){return function(e,t,s=[],i){const n=new Array(t.length),o=new Float32Array(2*t.length),r=new Float32Array(2*t.length),a=new Uint8Array(t.length);return t.forEach((e,t)=>{const s=2*t;n[t]=e.id,o[s]=e.x,o[s+1]=e.y,r[s]=e.vx,r[s+1]=e.vy,a[t]=e.sleeping?1:0}),{bodies:t,ids:n,positions:o,result:e,sediment:s,sleeping:a,snapshot:i,velocities:r}}(t,e.readBodies(),e.readSediment(),e.snapshot())}function qe(e){return Oe(e,e.tick(0))}var ke=function(){let e=new Me;return{handle(t){switch(t.type){case"init":return e=new Me(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:qe(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:qe(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:qe(e)};case"tick":return{type:"frame",frame:Oe(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:Oe(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:qe(e)};case"clear":return e.clear(),{type:"frame",frame:qe(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:qe(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:qe(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:qe(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:qe(e)}}}}}();function Pe(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:{message:String(e)}}self.onmessage=e=>{const t=e.data;try{const e=ke.handle(t.command);self.postMessage({ok:!0,payload:e,requestId:t.requestId},function(e){return"frame"===e.type||"removed"===e.type?[(t=e.frame).positions.buffer,t.velocities.buffer,t.sleeping.buffer]:[];var t}(e))}catch(e){self.postMessage({error:Pe(e),ok:!1,requestId:t.requestId})}};
|