semiotic 3.8.7 → 3.8.8
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/CLAUDE.md +2 -2
- package/README.md +56 -46
- package/ai/dist/mcp-server.js +28 -2
- package/ai/schema.json +124 -4
- package/ai/surface-manifest.json +1 -1
- package/ai/system-prompt.md +1 -1
- package/dist/{chunk-chartContainerDataAudit-JDSVSKGM.module.min.js → chunk-chartContainerDataAudit-IQ3NBN3Q.module.min.js} +1 -1
- package/dist/chunk-chunk-2B3AIKUZ.module.min.js +2 -0
- package/dist/chunk-chunk-2NVFEB7P.module.min.js +2 -0
- package/dist/chunk-chunk-3GCILWPB.module.min.js +2 -0
- package/dist/chunk-chunk-46KRGJQP.module.min.js +1 -0
- package/dist/{chunk-chunk-5SD6BHVW.module.min.js → chunk-chunk-4MLLQUGW.module.min.js} +1 -1
- package/dist/chunk-chunk-57RBPDBQ.module.min.js +2 -0
- package/dist/chunk-chunk-5VVNW5AZ.module.min.js +1 -0
- package/dist/chunk-chunk-66PCWJUG.module.min.js +1 -0
- package/dist/chunk-chunk-7LE56WAE.module.min.js +2 -0
- package/dist/chunk-chunk-7T25U75Z.module.min.js +2 -0
- package/dist/chunk-chunk-AF53TBSN.module.min.js +2 -0
- package/dist/chunk-chunk-BTZYH2IE.module.min.js +1 -0
- package/dist/chunk-chunk-BWV55BZK.module.min.js +2 -0
- package/dist/{chunk-chunk-FRO4TRXK.module.min.js → chunk-chunk-BZNOAHJV.module.min.js} +1 -1
- package/dist/chunk-chunk-CD6PVVS3.module.min.js +2 -0
- package/dist/chunk-chunk-DTSNLGRK.module.min.js +2 -0
- package/dist/{chunk-chunk-BNGBEY7N.module.min.js → chunk-chunk-FC3NZWYR.module.min.js} +1 -1
- package/dist/chunk-chunk-FEPXDKJP.module.min.js +1 -0
- package/dist/chunk-chunk-FJ76HWQZ.module.min.js +1 -0
- package/dist/chunk-chunk-FRGBMTZR.module.min.js +1 -0
- package/dist/chunk-chunk-G75OPF5N.module.min.js +2 -0
- package/dist/{chunk-chunk-NH4MEAKP.module.min.js → chunk-chunk-H5IFO6CU.module.min.js} +1 -1
- package/dist/chunk-chunk-HADHLMY5.module.min.js +1 -0
- package/dist/chunk-chunk-HBFA4NN6.module.min.js +1 -0
- package/dist/chunk-chunk-HCNDE26Q.module.min.js +2 -0
- package/dist/chunk-chunk-JJ4BSUYL.module.min.js +2 -0
- package/dist/chunk-chunk-JRHXQGEV.module.min.js +2 -0
- package/dist/chunk-chunk-L6FFYGYS.module.min.js +1 -0
- package/dist/{chunk-chunk-Z2AJERX5.module.min.js → chunk-chunk-LJDH3WV3.module.min.js} +1 -1
- package/dist/chunk-chunk-LSJUXBMF.module.min.js +1 -0
- package/dist/chunk-chunk-N3Q33XCB.module.min.js +2 -0
- package/dist/chunk-chunk-NWIGA3UK.module.min.js +1 -0
- package/dist/chunk-chunk-OG3TTJGJ.module.min.js +2 -0
- package/dist/{chunk-chunk-XEVJDUTH.module.min.js → chunk-chunk-OZK46A5U.module.min.js} +1 -1
- package/dist/chunk-chunk-PMR47KRY.module.min.js +2 -0
- package/dist/chunk-chunk-QQJNG23C.module.min.js +2 -0
- package/dist/{chunk-chunk-LG7YKJAK.module.min.js → chunk-chunk-RGJ6TKAH.module.min.js} +1 -1
- package/dist/{chunk-chunk-JWXLNZSM.module.min.js → chunk-chunk-SFLUSZ73.module.min.js} +1 -1
- package/dist/chunk-chunk-TCMHJWFJ.module.min.js +1 -0
- package/dist/{chunk-chunk-LVHDZAT3.module.min.js → chunk-chunk-UEZ6SHW5.module.min.js} +1 -1
- package/dist/chunk-chunk-VUWYT7DY.module.min.js +2 -0
- package/dist/{chunk-chunk-OI7R7EJB.module.min.js → chunk-chunk-W5HWGQMD.module.min.js} +1 -1
- package/dist/chunk-chunk-WFHZHWT7.module.min.js +1 -0
- package/dist/chunk-chunk-WGROBM3I.module.min.js +2 -0
- package/dist/{chunk-chunk-GU2EJIDJ.module.min.js → chunk-chunk-WSDJFBKX.module.min.js} +1 -1
- package/dist/chunk-statisticalOverlays-HMYYSGPE.module.min.js +2 -0
- package/dist/components/charts/index.d.ts +2 -2
- package/dist/components/charts/network/ProcessSankey.d.ts +105 -74
- package/dist/components/charts/network/processSankey/accessors.d.ts +7 -0
- package/dist/components/charts/network/processSankey/algorithm.d.ts +14 -193
- package/dist/components/charts/network/processSankey/axisChrome.d.ts +31 -0
- package/dist/components/charts/network/processSankey/bandPaths.d.ts +45 -0
- package/dist/components/charts/network/processSankey/buildScenes.d.ts +41 -3
- package/dist/components/charts/network/processSankey/fixtures.d.ts +17 -0
- package/dist/components/charts/network/processSankey/frameMargins.d.ts +11 -0
- package/dist/components/charts/network/processSankey/groupBonding.d.ts +13 -0
- package/dist/components/charts/network/processSankey/inventoryAtTime.d.ts +41 -0
- package/dist/components/charts/network/processSankey/labelPlacement.d.ts +34 -0
- package/dist/components/charts/network/processSankey/layoutGeometry.d.ts +47 -0
- package/dist/components/charts/network/processSankey/layoutOrchestrator.d.ts +44 -0
- package/dist/components/charts/network/processSankey/layoutQualityProduct.d.ts +27 -0
- package/dist/components/charts/network/processSankey/massSimulation.d.ts +16 -0
- package/dist/components/charts/network/processSankey/ordering.d.ts +55 -0
- package/dist/components/charts/network/processSankey/orderingBond.d.ts +33 -0
- package/dist/components/charts/network/processSankey/orientation.d.ts +5 -0
- package/dist/components/charts/network/processSankey/packing.d.ts +8 -0
- package/dist/components/charts/network/processSankey/packingCache.d.ts +23 -0
- package/dist/components/charts/network/processSankey/processSankeyLayoutAsync.d.ts +27 -0
- package/dist/components/charts/network/processSankey/processSankeyLayoutWorkerClient.d.ts +72 -0
- package/dist/components/charts/network/processSankey/processSankeyTooltip.d.ts +26 -0
- package/dist/components/charts/network/processSankey/processSankeyTypes.d.ts +163 -0
- package/dist/components/charts/network/processSankey/ribbonInputs.d.ts +26 -2
- package/dist/components/charts/network/processSankey/ribbonRunway.d.ts +45 -0
- package/dist/components/charts/network/processSankey/streamingLayout.d.ts +23 -0
- package/dist/components/charts/network/processSankey/time.d.ts +11 -0
- package/dist/components/charts/network/processSankey/useProcessSankeyPush.d.ts +29 -0
- package/dist/components/charts/network/processSankey/useProcessSankeyScenes.d.ts +26 -0
- package/dist/components/charts/network/processSankey/validation.d.ts +33 -0
- package/dist/components/charts/shared/chartFamilySets.d.ts +1 -0
- package/dist/components/charts/shared/formatUtils.d.ts +12 -1
- package/dist/components/charts/shared/hatchFill.d.ts +2 -0
- package/dist/components/charts/shared/hooks.d.ts +1 -1
- package/dist/components/charts/shared/leastSquaresRegression.d.ts +31 -0
- package/dist/components/charts/shared/styleRules.d.ts +5 -1
- package/dist/components/charts/shared/useChartLegend.d.ts +6 -0
- package/dist/components/charts/shared/useChartSetup.d.ts +1 -1
- package/dist/components/charts/shared/validateProps.d.ts +2 -2
- package/dist/components/charts/shared/withChartWrapper.d.ts +0 -6
- package/dist/components/data/numericFieldProfiler.d.ts +2 -0
- package/dist/components/recipes/layout1d.d.ts +68 -0
- package/dist/components/semiotic-network.d.ts +2 -2
- package/dist/components/semiotic-recipes-core.d.ts +2 -0
- package/dist/components/semiotic.d.ts +2 -0
- package/dist/components/server/staticSVGChrome.d.ts +2 -1
- package/dist/components/store/createStore.d.ts +2 -0
- package/dist/components/stream/OrdinalPipelineStore.d.ts +3 -0
- package/dist/components/stream/PipelineStore.d.ts +5 -0
- package/dist/components/stream/accessorUtils.d.ts +21 -0
- package/dist/components/stream/frameKeyboardNavigation.d.ts +3 -2
- package/dist/components/stream/layouts/forceLayoutWorkerClient.d.ts +3 -8
- package/dist/components/stream/layouts/index.d.ts +1 -1
- package/dist/components/stream/moduleWorkerSession.d.ts +67 -0
- package/dist/components/stream/networkTypes.d.ts +2 -0
- package/dist/components/stream/ordinalSceneBuilders/sceneBuilderMap.d.ts +2 -1
- package/dist/components/stream/physics/PhysicsKernel.d.ts +9 -0
- package/dist/components/stream/pipelineIntroCancellation.d.ts +6 -0
- package/dist/components/stream/pipelineTransitions.d.ts +15 -1
- package/dist/components/stream/renderers/canvasRenderHelpers.d.ts +16 -4
- package/dist/components/stream/renderers/symbolCanvasRenderer.d.ts +4 -0
- package/dist/components/stream/symbolPath.d.ts +8 -0
- package/dist/components/stream/types.d.ts +2 -0
- package/dist/components/stream/useCanvasFrameHost.d.ts +6 -0
- package/dist/components/stream/useSemanticFrameInteractions.d.ts +12 -3
- package/dist/components/stream/xyFrameAxisTypes.d.ts +4 -0
- package/dist/forceLayoutWorker.js +1 -1
- package/dist/geo.min.js +1 -1
- package/dist/geo.module.min.js +1 -1
- package/dist/network.min.js +1 -1
- package/dist/network.module.min.js +1 -1
- package/dist/ordinal.min.js +1 -1
- package/dist/ordinal.module.min.js +1 -1
- package/dist/physics.min.js +1 -1
- package/dist/physics.module.min.js +1 -1
- package/dist/physicsWorker.js +1 -1
- package/dist/processSankeyLayoutWorker.js +1 -0
- package/dist/realtime.min.js +1 -1
- package/dist/realtime.module.min.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.min.js +1 -1
- package/dist/semiotic-ai.module.min.js +1 -1
- package/dist/semiotic-experimental-vacp.min.js +1 -1
- package/dist/semiotic-experimental-vacp.module.min.js +1 -1
- package/dist/semiotic-experimental.min.js +1 -1
- package/dist/semiotic-experimental.module.min.js +1 -1
- package/dist/semiotic-network.d.ts +2 -2
- package/dist/semiotic-realtime-core.min.js +1 -1
- package/dist/semiotic-realtime-core.module.min.js +1 -1
- package/dist/semiotic-recipes-core.d.ts +2 -0
- package/dist/semiotic-recipes-core.min.js +1 -1
- package/dist/semiotic-recipes-core.module.min.js +1 -1
- package/dist/semiotic-recipes.min.js +1 -1
- package/dist/semiotic-recipes.module.min.js +1 -1
- package/dist/semiotic-server-edge.min.js +1 -1
- package/dist/semiotic-server-edge.module.min.js +1 -1
- package/dist/semiotic-server-node.min.js +1 -1
- package/dist/semiotic-server-node.module.min.js +1 -1
- package/dist/semiotic-themes-core.module.min.js +1 -1
- package/dist/semiotic-themes-react.module.min.js +1 -1
- package/dist/semiotic-themes.module.min.js +1 -1
- package/dist/semiotic-utils-core.min.js +1 -1
- package/dist/semiotic-utils-core.module.min.js +1 -1
- package/dist/semiotic-utils-react.module.min.js +1 -1
- package/dist/semiotic-utils.min.js +1 -1
- package/dist/semiotic-utils.module.min.js +1 -1
- package/dist/semiotic-value.min.js +1 -1
- package/dist/semiotic-value.module.min.js +1 -1
- package/dist/semiotic.d.ts +2 -0
- package/dist/semiotic.min.js +1 -1
- package/dist/semiotic.module.min.js +1 -1
- package/dist/server.min.js +1 -1
- package/dist/server.module.min.js +1 -1
- package/dist/xy.min.js +1 -1
- package/dist/xy.module.min.js +1 -1
- package/package.json +4 -3
- package/dist/chunk-chunk-2YAZHXL4.module.min.js +0 -2
- package/dist/chunk-chunk-3NGIKFD6.module.min.js +0 -1
- package/dist/chunk-chunk-7TTBHSAG.module.min.js +0 -2
- package/dist/chunk-chunk-7ZDJSYKI.module.min.js +0 -2
- package/dist/chunk-chunk-BGHPD3RA.module.min.js +0 -1
- package/dist/chunk-chunk-BMRZ2SPU.module.min.js +0 -2
- package/dist/chunk-chunk-C7APLVQD.module.min.js +0 -2
- package/dist/chunk-chunk-DGWFBOGB.module.min.js +0 -1
- package/dist/chunk-chunk-DIVE2DRA.module.min.js +0 -2
- package/dist/chunk-chunk-DSNGDNJY.module.min.js +0 -1
- package/dist/chunk-chunk-FBUNUIPV.module.min.js +0 -2
- package/dist/chunk-chunk-G7QVPZUD.module.min.js +0 -2
- package/dist/chunk-chunk-GBPYV4FP.module.min.js +0 -2
- package/dist/chunk-chunk-KXAFCCDB.module.min.js +0 -2
- package/dist/chunk-chunk-LWITSR2O.module.min.js +0 -2
- package/dist/chunk-chunk-MX35T6RX.module.min.js +0 -2
- package/dist/chunk-chunk-NJETWX42.module.min.js +0 -2
- package/dist/chunk-chunk-NW25WGLS.module.min.js +0 -2
- package/dist/chunk-chunk-ONMLEXHR.module.min.js +0 -2
- package/dist/chunk-chunk-OY66GCE6.module.min.js +0 -1
- package/dist/chunk-chunk-PRDGLMJT.module.min.js +0 -2
- package/dist/chunk-chunk-PZFT457G.module.min.js +0 -1
- package/dist/chunk-chunk-Q3WW6JGR.module.min.js +0 -1
- package/dist/chunk-chunk-Q6XKQTOQ.module.min.js +0 -1
- package/dist/chunk-chunk-RJRM2E6P.module.min.js +0 -1
- package/dist/chunk-chunk-RPL7WYXI.module.min.js +0 -1
- package/dist/chunk-chunk-V3OAKG32.module.min.js +0 -1
- package/dist/chunk-chunk-WCX6U47H.module.min.js +0 -2
- package/dist/chunk-chunk-WLOIUMWG.module.min.js +0 -2
- package/dist/chunk-chunk-XEGXX4F7.module.min.js +0 -1
- package/dist/chunk-chunk-XFRBLXYM.module.min.js +0 -1
- package/dist/chunk-chunk-ZXYDYAB7.module.min.js +0 -2
- package/dist/chunk-statisticalOverlays-6MVAK5RW.module.min.js +0 -2
- package/dist/components/stream/renderers/networkSymbolRenderer.d.ts +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{createProcessJourneyLedger as e,processJourneyRows as t,updateProcessJourney as n}from"./chunk-chunk-YWZB3KPI.module.min.js";import{ChainReactionChart as i,calculateBlockerAmplification as o,compileDependencyMachine as r,createLogicalJoin as s,replayStateTransitions as a,routeDependencyTracks as l}from"./chunk-chunk-FRO4TRXK.module.min.js";import{CollisionSwarmChart as u,CrucibleChart as c,DEFAULT_CRUCIBLE_HEIGHT as p,DEFAULT_CRUCIBLE_OUTLETS as h,DEFAULT_CRUCIBLE_SIZE as m,DEFAULT_CRUCIBLE_WIDTH as d,EventDropChart as f,GaltonBoardChart as y,GauntletChart as w,GuantletChart as g,PacketFlowChart as x,PhysicalFlowChart as b,PhysicsPileChart as v,ProcessFlowChart as k,UnitPileChart as M,applyCrucibleEvent as A,applyGauntletEffect as P,buildCrucibleEvidence as j,buildCrucibleInitialSpawns as E,buildCrucibleLayout as S,buildCruciblePhysicsConfig as $,buildCrucibleProductEvents as N,buildCrucibleProjection as R,buildCrucibleStateSpawns as D,buildCrucibleTerminalSpawns as I,cloneCrucibleState as q,compileCruciblePlan as W,createInitialCrucibleState as X,crucibleBondId as T,crucibleBoundaryColliders as Y,crucibleComponentBodyId as B,crucibleProductBodyId as C,crucibleProjectionRows as F,crucibleSemanticKey as O,defaultViability as Z,evaluateCrucibleConservation as J,eventLogItem as z,physicsProcessBoundaryColliders as H,physicsProcessGroupSemanticItems as K,physicsProcessRegionSemanticItem as L,physicsProcessStageSemanticItems as G,planGauntletPropertyWork as U,processChrome as V,recordGauntletEvent as _,replaceGauntletNegative as Q,replayCruciblePlan as ee,resolveCrucibleSelector as te,resolveCrucibleSnapshotAt as ne,resolveCrucibleTime as ie}from"./chunk-chunk-Z2AJERX5.module.min.js";import{BuiltInPhysicsEngineAdapter as oe,PhysicsCustomChart as re,PhysicsPipelineStore as se,PhysicsSVGOverlay as ae,PhysicsSedimentAccumulator as le,StreamPhysicsFrame as ue,StreamPhysicsFrame_default as ce,absorbRegion as pe,aggregateRegionCounts as he,bodiesToAnnotationAnchors as me,bodyGroupSpec as de,buildCollisionSwarmPhysics as fe,buildEventDropPhysics as ye,buildGaltonBoardPhysics as we,buildPhysicalFlowPhysics as ge,buildPhysicsAnnotationContext as xe,buildPhysicsPile as be,buildProcessFlowPhysics as ve,capacitatedRegion as ke,chargeGateRegion as Me,collidersFromPlotBounds as Ae,collidersFromXScaleBins as Pe,composePhysicsControllers as je,createCapacityQueueController as Ee,createDefaultPhysicsEngineAdapter as Se,createDependencyGateController as $e,createPortalController as Ne,createServiceLevelController as Re,createServiceResourcePoolController as De,evaluatePhysicsBodyBudget as Ie,forceFieldRegion as qe,groupCompletionRows as We,membraneRegion as Xe,normalizePhysicsAnnotations as Te,portalRegion as Ye,pressureFieldRegion as Be,processLaneWalls as Ce,processStageLayout as Fe,processStageRegions as Oe,processVolumePolygons as Ze,regionCountsToProjectionRows as Je,routeSurfaceRegion as ze,sedimentHeightfield as He,stageTargetInVolume as Ke}from"./chunk-chunk-NW25WGLS.module.min.js";import{mulberry32 as Le}from"./chunk-chunk-SIRIJ3DY.module.min.js";import{composeStyleRules as Ge,makeRuleValueResolver as Ue,matchesThreshold as Ve,resolveStyleRules as _e,ruleMatches as Qe}from"./chunk-chunk-EMO5NUGE.module.min.js";import"./chunk-chunk-SV4XAZ3Q.module.min.js";import"./chunk-chunk-JWXLNZSM.module.min.js";import{compileMotionEncoding as et,deriveMotionVector as tt,opacityFromAge as nt,resolveMotionAccessor as it,resolveMotionAge as ot,resolveMotionVector as rt}from"./chunk-chunk-5SD6BHVW.module.min.js";import{hatchFillId as st,hatchPatternDef as at,isHatchFill as lt,resolveSvgFill as ut}from"./chunk-chunk-7ZDJSYKI.module.min.js";import"./chunk-chunk-JJ2OOIET.module.min.js";import"./chunk-chunk-WCX6U47H.module.min.js";import"./chunk-chunk-KTWEBFMX.module.min.js";import"./chunk-chunk-ACLDBMRH.module.min.js";import"./chunk-chunk-YHNZCPOZ.module.min.js";function ct(e){const{data:t,encoding:n,defaults:i={},scales:o}=e,r=et({data:t,encoding:n}),s=[],a=new Map,l=[],u=[],c=new Map;return r.rows.forEach((e,t)=>{const{id:r,datum:p}=e,h=Math.max(0,it(n.appearance?.size,p,t)??i.size??6),m=it(n.appearance?.shape,p,t)??i.shape??{type:"circle",radius:h},d=e.placement.x??i.x??0,f=e.placement.y??i.y??0,y=o?.x?o.x(d):d,w=o?.y?o.y(f):f,g=it(n.appearance?.color,p,t)??i.color,x=it(n.appearance?.opacity,p,t)??i.opacity,b=it(n.appearance?.stroke,p,t)??i.stroke,v=it(n.appearance?.strokeWidth,p,t)??i.strokeWidth,k=it(n.time?.spawnAt,p,t)??e.time.arrival,M=e.kinematics.velocityX,A=e.kinematics.velocityY,P=it(n.dynamics?.mass,p,t)??i.mass??1,j=it(n.dynamics?.friction,p,t),E=it(n.dynamics?.restitution,p,t),S=it(n.dynamics?.bodyCollisions,p,t),$={id:r,x:y,y:w,mass:P,shape:{...m},datum:p,...null!=k&&{spawnAt:k},...null!=M&&{vx:M},...null!=A&&{vy:A},...null!=j&&{friction:j},...null!=E&&{restitution:E},...null!=S&&{bodyCollisions:S}},N={...null!=g&&{fill:g},...null!=x&&{opacity:x},...null!=b&&{stroke:b},...null!=v&&{strokeWidth:v}},R={id:r,datum:p,appearance:{color:g,opacity:x,shape:m,size:h,stroke:b,strokeWidth:v},placement:{x:y,y:w,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:k,spawnAt:k,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:M,velocityY:A,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:S,friction:j,mass:P,restitution:E},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:$};s.push(R),a.set(r,R),l.push($),c.set(r,N),u.push({id:r,bodyId:r,label:e.accessible.label,description:e.accessible.description,datum:p,x:y,y:w,group:e.accessible.group})}),{rows:s,byId:a,spawns:l,semanticItems:u,bodyStyle:e=>c.get(e.id)??{}}}function pt(e){return t=>{const n=ct({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),i=e.extend?.(t,n)??{};return{...i,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...i.semanticItems??[]]}}}function ht(e,t){const{layout:n,positiveProperties:i,negativeProperties:o,viability:r,outcome:s}=t,a=function(e){return new Map(e.gates.map(e=>[e.id,e]))}(n),l=[...("function"==typeof t.events?t.events(e,n):t.events)??[]].sort((e,t)=>e.time-t.time);let u=e;for(const e of l){const t=e.gateId?a.get(e.gateId):void 0,l=e.effects??[],c={...z(e,l),appliedAt:e.time},p=_(u,c);if(p!==u){u=p;for(const n of l){const r={event:e,gate:t,negativeProperties:o,positiveProperties:i,project:u};n.when&&!n.when(r)||(u=P(u,n,r))}u={...u,viability:r?.(u,{negativeProperties:o,positiveProperties:i})??Z(u,i,o)},e.final&&(u={...u,outcome:e.outcome??s?.(u,{layout:n,negativeProperties:o,positiveProperties:i})??(u.viability>20?"built":"approved_not_built")})}}return u}function mt(e){return e.projects.map(t=>ht(t,e))}var dt=[.1,.5,.9],ft=1e6;function yt(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function wt(e,t,n,i,o){return"function"==typeof i?i(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,i??o)}function gt(e){const t=Number(e.toFixed(12));return Object.is(t,-0)?0:t}function xt(e,t,n,i){const o=e.flatMap((e,o)=>{const r=yt(wt(e,o,t,n,"time")),s=yt(wt(e,o,t,i,"value"));return null==r||null==s?[]:[{time:gt(r),value:s,index:o}]});o.sort((e,t)=>e.time-t.time||e.index-t.index);const r=[];for(const e of o){const t=r[r.length-1];t?.time===e.time?t.value=e.value:r.push({time:e.time,value:e.value})}return r}function bt(e,t,n,i){if(!e.length)return null;const o=e[0],r=e[e.length-1];if(o.time>t)return"clamp"===i?o.value:null;if(t>r.time)return"clamp"===i?r.value:null;const s=function(e,t){let n=0,i=e.length;for(;i>n;){const o=n+i>>>1;t>e[o].time?n=o+1:i=o}return n}(e,t),a=e[s];if(a?.time===t)return a.value;const l=e[Math.max(0,s-1)];return"step"!==n&&a&&a.time!==l.time?l.value+(t-l.time)/(a.time-l.time)*(a.value-l.value):l.value}function vt(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,i=Math.floor(n),o=Math.ceil(n);return i===o?e[i]:e[i]+(e[o]-e[i])*(n-i)}function kt(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",i=function(e){const t=(e??dt).map(e=>{const t=yt(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return gt(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),o=function(e){if(Array.isArray(e)){if(e.length>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(e.map(yt).filter(e=>null!=e).map(gt))).sort((e,t)=>e-t)}const t=e,n=yt(t.start),i=yt(t.end),o=yt(t.step);if(null==n||null==i||null==o||0>=o||n>i)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const r=Math.floor((i-n)/o)+1;if(r>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");const s=[],a=1e-10*Math.max(1,Math.abs(i),Math.abs(n));for(let e=0;r>e;e+=1){const t=n+e*o;if(t>i+a)break;s.push(gt(Math.min(t,i)))}if(s.length&&a>=Math.abs(s[s.length-1]-i)||s.push(gt(i)),s.length>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(s)).sort((e,t)=>e-t)}(e.sampleAt),r=e.runs.map(t=>xt(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:o.map(e=>{const o=r.map(i=>bt(i,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),s={};for(const e of i)s[e]=o.length?vt(o,e):null;return{time:e,count:o.length,min:o.length?o[0]:null,max:o.length?o[o.length-1]:null,median:o.length?vt(o,.5):null,quantiles:s}}),quantiles:i,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function Mt(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function At(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=yt(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const i=gt(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,i))throw Error(`comparePhysicsTrace could not find quantile ${i} in the reference envelope`);return e.quantiles[i]??null}function Pt(e,t,n){return t>e?"below":e>n?"above":"inside"}function jt(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const i=e.value-e.lower,o=t.value-t.lower,r=e.value-e.upper,s=t.value-t.upper,a=[0,1];for(const[e,t]of[[i,o],[r,s]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let l=0,u=0,c=0;for(let i=0;a.length-1>i;i+=1){const o=a[i],r=a[i+1];if(o>=r)continue;const s=(o+r)/2,p=(r-o)*n,h=Pt(e.value+(t.value-e.value)*s,e.lower+(t.lower-e.lower)*s,e.upper+(t.upper-e.upper)*s);"below"===h?l+=p:"above"===h?c+=p:u+=p}return{below:l,inside:u,above:c,observed:n}}function Et(e,t,n={}){const i=n.interpolation??t.interpolation,o=n.outsideDomain??t.outsideDomain,r=xt(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),s=n.lower??Mt(t,"lower"),a=n.upper??Mt(t,"upper"),l=t.points.map(e=>{const t=bt(r,e.time,i,o),n=At(e,s),l=At(e,a);if(null!=n&&null!=l&&n>l)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:l,status:null==t||null==n||null==l?"unobserved":Pt(t,n,l)}});let u=0,c=0,p=0,h=0,m=null,d=0,f=null;for(const e of l){if("below"===e.status?u+=1:"inside"===e.status?c+=1:"above"===e.status&&(p+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,m=e.time),n>d&&(d=n,f=e.time)}let y=0,w=0,g=0,x=0;for(let e=0;l.length-1>e;e+=1){const t=l[e],n=l[e+1],o=Math.max(0,n.time-t.time);if(o>0){if("linear"===i){const e=jt(t,n);y+=e.below,w+=e.inside,g+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=o,"below"===t.status?y+=o:"above"===t.status?g+=o:w+=o)}}const b=l[0]?.time,v=l[l.length-1]?.time,k=null==b||null==v?0:Math.max(0,v-b);return{points:l,sampleCount:l.length,observedSamples:u+c+p,belowSamples:u,insideSamples:c,aboveSamples:p,totalDuration:k,observedDuration:x,unobservedDuration:Math.max(0,k-x),belowDuration:y,insideDuration:w,aboveDuration:g,peakExcess:h,peakExcessAt:m,peakDeficit:d,peakDeficitAt:f}}function St(e){const[t,n]=e.size,i=e.flow??"down",o=null==(v=e.padding)?{top:24,right:24,bottom:24,left:24}:"number"==typeof v?{top:v,right:v,bottom:v,left:v}:{top:v.top??0,right:v.right??0,bottom:v.bottom??0,left:v.left??0},r=Math.max(.05,Math.min(1,e.channelRatio??1)),s={x:o.left,y:o.top,width:Math.max(1,t-o.left-o.right),height:Math.max(1,n-o.top-o.bottom)},a="down"===i?s.height:s.width,l=a*Math.max(0,e.chargeExtent??.12),u=a*Math.max(0,e.projectionExtent??0),c=a*Math.max(0,e.destinationExtent??.55),p=Math.max(0,a-l-c-u),h=function(e){return"number"==typeof e?Array.from({length:Math.max(1,Math.round(e))},(e,t)=>({id:"bin-"+t,label:t+""})):0===e.length?[{id:"bin-0",label:"0"}]:e.map((e,t)=>({id:e.id,label:e.label??e.id??t+""}))}(e.destinations),m=("down"===i?s.width:s.height)/h.length,d="down"===i?(e,t)=>({x:s.x,y:s.y+e,width:s.width,height:t}):(e,t)=>({x:s.x+e,y:s.y,width:t,height:s.height}),f=d(0,l),y=d(l,p),w=l+p,g=d(w,c),x=d(w+c,u),b=h.map((e,t)=>{const n=t*m,o=m*r,a=(m-o)/2;return"down"===i?{id:e.id,label:e.label,order:t,x:s.x+n+a,y:g.y,width:o,height:g.height,centerX:s.x+(t+.5)*m,centerY:g.y+g.height/2}:{id:e.id,label:e.label,order:t,x:g.x,y:s.y+n+a,width:g.width,height:o,centerX:g.x+g.width/2,centerY:s.y+(t+.5)*m}});var v;return{width:t,height:n,flow:i,charge:f,apparatus:y,destinations:b,projection:x}}function $t(e,t){return e.destinations.find(e=>e.id===t)}function Nt(e,t,n){const{charge:i,flow:o}=e,r=Math.max(1,n),s=(t%r+.5)/r;return"down"===o?{x:i.x+i.width*s,y:i.y+i.height/2}:{x:i.x+i.width/2,y:i.y+i.height*s}}function Rt(e,t={}){const n=t.thickness??4,i=t.idPrefix??"stage",{destinations:o,flow:r,width:s,height:a}=e,l=[];if(o.length>0){const t=o[0];if("down"===r){const r=t.y+t.height;l.push({id:i+"-floor",shape:{type:"segment",x1:e.charge.x,y1:r,x2:e.charge.x+e.charge.width,y2:r,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerX-(o[e].centerX-o[e-1].centerX)/2;l.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:s,y1:t.y,x2:s,y2:r,thickness:n}})}}else{const r=t.x+t.width;l.push({id:i+"-floor",shape:{type:"segment",x1:r,y1:e.charge.y,x2:r,y2:e.charge.y+e.charge.height,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerY-(o[e].centerY-o[e-1].centerY)/2;l.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:t.x,y1:s,x2:r,y2:s,thickness:n}})}}}return!1!==t.walls&&l.push({id:i+"-wall-left",shape:{type:"segment",x1:1,y1:0,x2:1,y2:a,thickness:n}},{id:i+"-wall-right",shape:{type:"segment",x1:s-1,y1:0,x2:s-1,y2:a,thickness:n}}),l}function Dt(e,t={}){return`${t.charge??"bodies"} enter at the ${"down"===e.flow?"top":"left"}, travel ${"down"===e.flow?"downward":"left to right"} through ${t.apparatus??"the apparatus"}, and come to rest in ${e.destinations.length} ${t.destination??"destinations"}: ${e.destinations.map(e=>e.label).join(", ")}.`}function It(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function qt(e,t,n,i){const o="function"==typeof e?e(t,n):e;return Number.isFinite(o)?Number(o):i}function Wt(e,t,n){return It(e[t])??n}function Xt(e,t){return"number"==typeof e?e:e?.[t]??0}function Tt(e){const{band:t,idPrefix:n,plot:i,projection:o}=e,{includeBoundaryWalls:r=!0,includeInteriorWalls:s=!0,wallThickness:a=4}=t,l=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const i of e.values){const o=e.scale(i);Number.isFinite(o)&&(n.add(Number(o)),n.add(Number(o)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>l.length)return[];const u=r?l.length-1:l.length-2,c=[];for(let e=r?0:1;u>=e;e+=1){if(!s&&e>0&&l.length-1>e)continue;const t=l[e];c.push({id:`${n}-wall-${e}`,shape:"x"===o?{type:"aabb",x:t,y:i.y+i.height/2,width:a,height:i.height}:{type:"aabb",x:i.x+i.width/2,y:t,width:i.width,height:a}})}return c}function Yt(e){const{plot:t,idPrefix:n="physics-scale",bounds:i={},xBins:o,xBands:r,yBands:s}=e,a=[];if(!1!==i&&a.push(...Ae(t,{idPrefix:n,...i})),o){const{idPrefix:e,yTop:i,yBottom:r,...s}=o;a.push(...Pe({...s,idPrefix:e??n+"-xbin",yTop:i??t.y,yBottom:r??t.y+t.height}))}return r&&a.push(...Tt({band:r,idPrefix:r.idPrefix??n+"-xband",plot:t,projection:"x"})),s&&a.push(...Tt({band:s,idPrefix:s.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function Bt(e){const{plot:t,rows:n,columns:i=n+1,pegRadius:o=3,idPrefix:r="galton-peg",yStart:s=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:l=!0,restitution:u=.2,friction:c=.04}=e,p=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(i));if(0===p)return[];const m=p>1?(a-s)/(p-1):0,d=t.width/h,f=[];for(let e=0;p>e;e+=1){const n=l&&e%2==1?d/2:0;for(let i=0;h>i;i+=1){const a=t.x+d*(i+.5)+n;t.x+o>a||a>t.x+t.width-o||f.push({id:`${r}-${e}-${i}`,shape:{type:"aabb",x:a,y:s+e*m,width:2*o,height:2*o},restitution:u,friction:c})}}return f}function Ct(e,t={}){const{idPrefix:n="physics-token",radius:i=5,shape:o,mass:r,vx:s,vy:a,spawnAt:l,seed:u=1,jitter:c,datum:p}=t,h=Le(u),m=Xt(c,"x"),d=Xt(c,"y");return e.map((e,u)=>{const c=qt(t.x,e,u,Wt(e,"x",0)),f=qt(t.y,e,u,Wt(e,"y",0)),y=qt(i,e,u,5),w="function"==typeof o?o(e,u):o??{type:"circle",radius:y};return{id:`${n}-${e.index??u}`,x:c+(h()-.5)*m,y:f+(h()-.5)*d,vx:qt(s,e,u,0),vy:qt(a,e,u,0),mass:qt(r,e,u,1),spawnAt:qt(l,e,u,void 0),shape:w,datum:p?p(e,u):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function Ft(e,t={}){const{idPrefix:n="sediment",collider:i=!0,colliderThickness:o=1,restitution:r=.05,friction:s=.2,...a}=t,l=He(e,a),u=i?l.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+o/2,width:e.width,height:o},restitution:r,friction:s})):[];return{columns:l,colliders:u}}function Ot(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:i=1,startAt:o=0,rebase:r=!0,sort:s=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return It("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),l=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:o+(r?t-l:t)})).sort((e,t)=>s?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:o,timeAccessor:"spawnAt",timeScale:i}}}var Zt=ce;export{oe as BuiltInPhysicsEngineAdapter,i as ChainReactionChart,u as CollisionSwarmChart,c as CrucibleChart,p as DEFAULT_CRUCIBLE_HEIGHT,h as DEFAULT_CRUCIBLE_OUTLETS,m as DEFAULT_CRUCIBLE_SIZE,d as DEFAULT_CRUCIBLE_WIDTH,f as EventDropChart,y as GaltonBoardChart,w as GauntletChart,g as GuantletChart,x as PacketFlowChart,b as PhysicalFlowChart,re as PhysicsCustomChart,v as PhysicsPileChart,se as PhysicsPipelineStore,ae as PhysicsSVGOverlay,le as PhysicsSedimentAccumulator,k as ProcessFlowChart,ue as StreamPhysicsFrame,M as UnitPileChart,pe as absorbRegion,he as aggregateRegionCounts,A as applyCrucibleEvent,Ot as arrivalReplay,me as bodiesToAnnotationAnchors,de as bodyGroupSpec,fe as buildCollisionSwarmPhysics,j as buildCrucibleEvidence,E as buildCrucibleInitialSpawns,S as buildCrucibleLayout,$ as buildCruciblePhysicsConfig,N as buildCrucibleProductEvents,R as buildCrucibleProjection,D as buildCrucibleStateSpawns,I as buildCrucibleTerminalSpawns,ye as buildEventDropPhysics,we as buildGaltonBoardPhysics,ge as buildPhysicalFlowPhysics,xe as buildPhysicsAnnotationContext,be as buildPhysicsPile,ve as buildProcessFlowPhysics,o as calculateBlockerAmplification,ke as capacitatedRegion,Me as chargeGateRegion,q as cloneCrucibleState,Yt as collidersFromScales,Et as comparePhysicsTrace,W as compileCruciblePlan,r as compileDependencyMachine,et as compileMotionEncoding,ct as compilePhysicsEncoding,je as composePhysicsControllers,Ge as composeStyleRules,Ee as createCapacityQueueController,Se as createDefaultPhysicsEngineAdapter,$e as createDependencyGateController,X as createInitialCrucibleState,s as createLogicalJoin,pt as createPhysicsEncodingLayout,Ne as createPortalController,e as createProcessJourneyLedger,Re as createServiceLevelController,De as createServiceResourcePoolController,T as crucibleBondId,Y as crucibleBoundaryColliders,B as crucibleComponentBodyId,C as crucibleProductBodyId,F as crucibleProjectionRows,O as crucibleSemanticKey,Zt as default,tt as deriveMotionVector,Dt as describePhysicsStageGeography,J as evaluateCrucibleConservation,Ie as evaluatePhysicsBodyBudget,qe as forceFieldRegion,Bt as galtonPegs,We as groupCompletionRows,st as hatchFillId,at as hatchPatternDef,lt as isHatchFill,Ue as makeRuleValueResolver,Ve as matchesThreshold,Xe as membraneRegion,Te as normalizePhysicsAnnotations,nt as opacityFromAge,Nt as physicsChargePoint,$t as physicsDestination,H as physicsProcessBoundaryColliders,K as physicsProcessGroupSemanticItems,L as physicsProcessRegionSemanticItem,G as physicsProcessStageSemanticItems,kt as physicsReferenceEnvelope,Rt as physicsStageColliders,St as physicsStageGeography,U as planGauntletPropertyWork,Ye as portalRegion,Be as pressureFieldRegion,V as processChrome,t as processJourneyRows,Ce as processLaneWalls,Fe as processStageLayout,Oe as processStageRegions,Ze as processVolumePolygons,Je as regionCountsToProjectionRows,Q as replaceGauntletNegative,ee as replayCruciblePlan,a as replayStateTransitions,te as resolveCrucibleSelector,ne as resolveCrucibleSnapshotAt,ie as resolveCrucibleTime,ht as resolveGauntletTerminalState,mt as resolveGauntletTerminalStates,it as resolveMotionAccessor,ot as resolveMotionAge,rt as resolveMotionVector,_e as resolveStyleRules,ut as resolveSvgFill,l as routeDependencyTracks,ze as routeSurfaceRegion,Qe as ruleMatches,Ft as sedimentBake,He as sedimentHeightfield,Ct as spawnFromTokens,Ke as stageTargetInVolume,n as updateProcessJourney};
|
|
2
|
+
import{createProcessJourneyLedger as e,processJourneyRows as t,updateProcessJourney as n}from"./chunk-chunk-YWZB3KPI.module.min.js";import{ChainReactionChart as i,calculateBlockerAmplification as o,compileDependencyMachine as r,createLogicalJoin as s,replayStateTransitions as a,routeDependencyTracks as l}from"./chunk-chunk-BZNOAHJV.module.min.js";import{CollisionSwarmChart as u,CrucibleChart as c,DEFAULT_CRUCIBLE_HEIGHT as p,DEFAULT_CRUCIBLE_OUTLETS as h,DEFAULT_CRUCIBLE_SIZE as m,DEFAULT_CRUCIBLE_WIDTH as d,EventDropChart as f,GaltonBoardChart as y,GauntletChart as w,GuantletChart as g,PacketFlowChart as x,PhysicalFlowChart as b,PhysicsPileChart as v,ProcessFlowChart as k,UnitPileChart as M,applyCrucibleEvent as A,applyGauntletEffect as P,buildCrucibleEvidence as j,buildCrucibleInitialSpawns as E,buildCrucibleLayout as S,buildCruciblePhysicsConfig as $,buildCrucibleProductEvents as N,buildCrucibleProjection as R,buildCrucibleStateSpawns as D,buildCrucibleTerminalSpawns as I,cloneCrucibleState as q,compileCruciblePlan as B,createInitialCrucibleState as Y,crucibleBondId as W,crucibleBoundaryColliders as F,crucibleComponentBodyId as T,crucibleProductBodyId as X,crucibleProjectionRows as C,crucibleSemanticKey as L,defaultViability as O,evaluateCrucibleConservation as Z,eventLogItem as H,physicsProcessBoundaryColliders as J,physicsProcessGroupSemanticItems as z,physicsProcessRegionSemanticItem as U,physicsProcessStageSemanticItems as V,planGauntletPropertyWork as K,processChrome as Q,recordGauntletEvent as G,replaceGauntletNegative as _,replayCruciblePlan as ee,resolveCrucibleSelector as te,resolveCrucibleSnapshotAt as ne,resolveCrucibleTime as ie}from"./chunk-chunk-LJDH3WV3.module.min.js";import{BuiltInPhysicsEngineAdapter as oe,PhysicsCustomChart as re,PhysicsPipelineStore as se,PhysicsSVGOverlay as ae,PhysicsSedimentAccumulator as le,StreamPhysicsFrame as ue,StreamPhysicsFrame_default as ce,absorbRegion as pe,aggregateRegionCounts as he,bodiesToAnnotationAnchors as me,bodyGroupSpec as de,buildCollisionSwarmPhysics as fe,buildEventDropPhysics as ye,buildGaltonBoardPhysics as we,buildPhysicalFlowPhysics as ge,buildPhysicsAnnotationContext as xe,buildPhysicsPile as be,buildProcessFlowPhysics as ve,capacitatedRegion as ke,chargeGateRegion as Me,collidersFromPlotBounds as Ae,collidersFromXScaleBins as Pe,composePhysicsControllers as je,createCapacityQueueController as Ee,createDefaultPhysicsEngineAdapter as Se,createDependencyGateController as $e,createPortalController as Ne,createServiceLevelController as Re,createServiceResourcePoolController as De,evaluatePhysicsBodyBudget as Ie,forceFieldRegion as qe,groupCompletionRows as Be,membraneRegion as Ye,normalizePhysicsAnnotations as We,portalRegion as Fe,pressureFieldRegion as Te,processLaneWalls as Xe,processStageLayout as Ce,processStageRegions as Le,processVolumePolygons as Oe,regionCountsToProjectionRows as Ze,routeSurfaceRegion as He,sedimentHeightfield as Je,stageTargetInVolume as ze}from"./chunk-chunk-JJ4BSUYL.module.min.js";import{mulberry32 as Ue}from"./chunk-chunk-SIRIJ3DY.module.min.js";import{composeStyleRules as Ve,makeRuleValueResolver as Ke,matchesThreshold as Qe,resolveStyleRules as Ge,ruleMatches as _e}from"./chunk-chunk-EMO5NUGE.module.min.js";import"./chunk-chunk-SV4XAZ3Q.module.min.js";import"./chunk-chunk-SFLUSZ73.module.min.js";import{compileMotionEncoding as et,deriveMotionVector as tt,opacityFromAge as nt,resolveMotionAccessor as it,resolveMotionAge as ot,resolveMotionVector as rt}from"./chunk-chunk-4MLLQUGW.module.min.js";import{hatchFillId as st,hatchPatternDef as at,isHatchFill as lt,resolveSvgFill as ut}from"./chunk-chunk-HCNDE26Q.module.min.js";import"./chunk-chunk-2NVFEB7P.module.min.js";import"./chunk-chunk-PMR47KRY.module.min.js";import"./chunk-chunk-KTWEBFMX.module.min.js";import"./chunk-chunk-ACLDBMRH.module.min.js";import"./chunk-chunk-YHNZCPOZ.module.min.js";function ct(e){const{data:t,encoding:n,defaults:i={},scales:o}=e,r=et({data:t,encoding:n}),s=[],a=new Map,l=[],u=[],c=new Map;return r.rows.forEach((e,t)=>{const{id:r,datum:p}=e,h=Math.max(0,it(n.appearance?.size,p,t)??i.size??6),m=it(n.appearance?.shape,p,t)??i.shape??{type:"circle",radius:h},d=e.placement.x??i.x??0,f=e.placement.y??i.y??0,y=o?.x?o.x(d):d,w=o?.y?o.y(f):f,g=it(n.appearance?.color,p,t)??i.color,x=it(n.appearance?.opacity,p,t)??i.opacity,b=it(n.appearance?.stroke,p,t)??i.stroke,v=it(n.appearance?.strokeWidth,p,t)??i.strokeWidth,k=it(n.time?.spawnAt,p,t)??e.time.arrival,M=e.kinematics.velocityX,A=e.kinematics.velocityY,P=it(n.dynamics?.mass,p,t)??i.mass??1,j=it(n.dynamics?.friction,p,t),E=it(n.dynamics?.restitution,p,t),S=it(n.dynamics?.bodyCollisions,p,t),$={id:r,x:y,y:w,mass:P,shape:{...m},datum:p,...null!=k&&{spawnAt:k},...null!=M&&{vx:M},...null!=A&&{vy:A},...null!=j&&{friction:j},...null!=E&&{restitution:E},...null!=S&&{bodyCollisions:S}},N={...null!=g&&{fill:g},...null!=x&&{opacity:x},...null!=b&&{stroke:b},...null!=v&&{strokeWidth:v}},R={id:r,datum:p,appearance:{color:g,opacity:x,shape:m,size:h,stroke:b,strokeWidth:v},placement:{x:y,y:w,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:k,spawnAt:k,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:M,velocityY:A,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:S,friction:j,mass:P,restitution:E},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:$};s.push(R),a.set(r,R),l.push($),c.set(r,N),u.push({id:r,bodyId:r,label:e.accessible.label,description:e.accessible.description,datum:p,x:y,y:w,group:e.accessible.group})}),{rows:s,byId:a,spawns:l,semanticItems:u,bodyStyle:e=>c.get(e.id)??{}}}function pt(e){return t=>{const n=ct({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),i=e.extend?.(t,n)??{};return{...i,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...i.semanticItems??[]]}}}function ht(e,t){const{layout:n,positiveProperties:i,negativeProperties:o,viability:r,outcome:s}=t,a=function(e){return new Map(e.gates.map(e=>[e.id,e]))}(n),l=[...("function"==typeof t.events?t.events(e,n):t.events)??[]].sort((e,t)=>e.time-t.time);let u=e;for(const e of l){const t=e.gateId?a.get(e.gateId):void 0,l=e.effects??[],c={...H(e,l),appliedAt:e.time},p=G(u,c);if(p!==u){u=p;for(const n of l){const r={event:e,gate:t,negativeProperties:o,positiveProperties:i,project:u};n.when&&!n.when(r)||(u=P(u,n,r))}u={...u,viability:r?.(u,{negativeProperties:o,positiveProperties:i})??O(u,i,o)},e.final&&(u={...u,outcome:e.outcome??s?.(u,{layout:n,negativeProperties:o,positiveProperties:i})??(u.viability>20?"built":"approved_not_built")})}}return u}function mt(e){return e.projects.map(t=>ht(t,e))}var dt=[.1,.5,.9],ft=1e6;function yt(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function wt(e,t,n,i,o){return"function"==typeof i?i(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,i??o)}function gt(e){const t=Number(e.toFixed(12));return Object.is(t,-0)?0:t}function xt(e,t,n,i){const o=e.flatMap((e,o)=>{const r=yt(wt(e,o,t,n,"time")),s=yt(wt(e,o,t,i,"value"));return null==r||null==s?[]:[{time:gt(r),value:s,index:o}]});o.sort((e,t)=>e.time-t.time||e.index-t.index);const r=[];for(const e of o){const t=r[r.length-1];t?.time===e.time?t.value=e.value:r.push({time:e.time,value:e.value})}return r}function bt(e,t,n,i){if(!e.length)return null;const o=e[0],r=e[e.length-1];if(o.time>t)return"clamp"===i?o.value:null;if(t>r.time)return"clamp"===i?r.value:null;const s=function(e,t){let n=0,i=e.length;for(;i>n;){const o=n+i>>>1;t>e[o].time?n=o+1:i=o}return n}(e,t),a=e[s];if(a?.time===t)return a.value;const l=e[Math.max(0,s-1)];return"step"!==n&&a&&a.time!==l.time?l.value+(t-l.time)/(a.time-l.time)*(a.value-l.value):l.value}function vt(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,i=Math.floor(n),o=Math.ceil(n);return i===o?e[i]:e[i]+(e[o]-e[i])*(n-i)}function kt(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",i=function(e){const t=(e??dt).map(e=>{const t=yt(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return gt(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),o=function(e){if(Array.isArray(e)){if(e.length>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(e.map(yt).filter(e=>null!=e).map(gt))).sort((e,t)=>e-t)}const t=e,n=yt(t.start),i=yt(t.end),o=yt(t.step);if(null==n||null==i||null==o||0>=o||n>i)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const r=Math.floor((i-n)/o)+1;if(r>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");const s=[],a=1e-10*Math.max(1,Math.abs(i),Math.abs(n));for(let e=0;r>e;e+=1){const t=n+e*o;if(t>i+a)break;s.push(gt(Math.min(t,i)))}if(s.length&&a>=Math.abs(s[s.length-1]-i)||s.push(gt(i)),s.length>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(s)).sort((e,t)=>e-t)}(e.sampleAt),r=e.runs.map(t=>xt(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:o.map(e=>{const o=r.map(i=>bt(i,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),s={};for(const e of i)s[e]=o.length?vt(o,e):null;return{time:e,count:o.length,min:o.length?o[0]:null,max:o.length?o[o.length-1]:null,median:o.length?vt(o,.5):null,quantiles:s}}),quantiles:i,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function Mt(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function At(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=yt(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const i=gt(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,i))throw Error(`comparePhysicsTrace could not find quantile ${i} in the reference envelope`);return e.quantiles[i]??null}function Pt(e,t,n){return t>e?"below":e>n?"above":"inside"}function jt(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const i=e.value-e.lower,o=t.value-t.lower,r=e.value-e.upper,s=t.value-t.upper,a=[0,1];for(const[e,t]of[[i,o],[r,s]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let l=0,u=0,c=0;for(let i=0;a.length-1>i;i+=1){const o=a[i],r=a[i+1];if(o>=r)continue;const s=(o+r)/2,p=(r-o)*n,h=Pt(e.value+(t.value-e.value)*s,e.lower+(t.lower-e.lower)*s,e.upper+(t.upper-e.upper)*s);"below"===h?l+=p:"above"===h?c+=p:u+=p}return{below:l,inside:u,above:c,observed:n}}function Et(e,t,n={}){const i=n.interpolation??t.interpolation,o=n.outsideDomain??t.outsideDomain,r=xt(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),s=n.lower??Mt(t,"lower"),a=n.upper??Mt(t,"upper"),l=t.points.map(e=>{const t=bt(r,e.time,i,o),n=At(e,s),l=At(e,a);if(null!=n&&null!=l&&n>l)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:l,status:null==t||null==n||null==l?"unobserved":Pt(t,n,l)}});let u=0,c=0,p=0,h=0,m=null,d=0,f=null;for(const e of l){if("below"===e.status?u+=1:"inside"===e.status?c+=1:"above"===e.status&&(p+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,m=e.time),n>d&&(d=n,f=e.time)}let y=0,w=0,g=0,x=0;for(let e=0;l.length-1>e;e+=1){const t=l[e],n=l[e+1],o=Math.max(0,n.time-t.time);if(o>0){if("linear"===i){const e=jt(t,n);y+=e.below,w+=e.inside,g+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=o,"below"===t.status?y+=o:"above"===t.status?g+=o:w+=o)}}const b=l[0]?.time,v=l[l.length-1]?.time,k=null==b||null==v?0:Math.max(0,v-b);return{points:l,sampleCount:l.length,observedSamples:u+c+p,belowSamples:u,insideSamples:c,aboveSamples:p,totalDuration:k,observedDuration:x,unobservedDuration:Math.max(0,k-x),belowDuration:y,insideDuration:w,aboveDuration:g,peakExcess:h,peakExcessAt:m,peakDeficit:d,peakDeficitAt:f}}function St(e){const[t,n]=e.size,i=e.flow??"down",o=null==(v=e.padding)?{top:24,right:24,bottom:24,left:24}:"number"==typeof v?{top:v,right:v,bottom:v,left:v}:{top:v.top??0,right:v.right??0,bottom:v.bottom??0,left:v.left??0},r=Math.max(.05,Math.min(1,e.channelRatio??1)),s={x:o.left,y:o.top,width:Math.max(1,t-o.left-o.right),height:Math.max(1,n-o.top-o.bottom)},a="down"===i?s.height:s.width,l=a*Math.max(0,e.chargeExtent??.12),u=a*Math.max(0,e.projectionExtent??0),c=a*Math.max(0,e.destinationExtent??.55),p=Math.max(0,a-l-c-u),h=function(e){return"number"==typeof e?Array.from({length:Math.max(1,Math.round(e))},(e,t)=>({id:"bin-"+t,label:t+""})):0===e.length?[{id:"bin-0",label:"0"}]:e.map((e,t)=>({id:e.id,label:e.label??e.id??t+""}))}(e.destinations),m=("down"===i?s.width:s.height)/h.length,d="down"===i?(e,t)=>({x:s.x,y:s.y+e,width:s.width,height:t}):(e,t)=>({x:s.x+e,y:s.y,width:t,height:s.height}),f=d(0,l),y=d(l,p),w=l+p,g=d(w,c),x=d(w+c,u),b=h.map((e,t)=>{const n=t*m,o=m*r,a=(m-o)/2;return"down"===i?{id:e.id,label:e.label,order:t,x:s.x+n+a,y:g.y,width:o,height:g.height,centerX:s.x+(t+.5)*m,centerY:g.y+g.height/2}:{id:e.id,label:e.label,order:t,x:g.x,y:s.y+n+a,width:g.width,height:o,centerX:g.x+g.width/2,centerY:s.y+(t+.5)*m}});var v;return{width:t,height:n,flow:i,charge:f,apparatus:y,destinations:b,projection:x}}function $t(e,t){return e.destinations.find(e=>e.id===t)}function Nt(e,t,n){const{charge:i,flow:o}=e,r=Math.max(1,n),s=(t%r+.5)/r;return"down"===o?{x:i.x+i.width*s,y:i.y+i.height/2}:{x:i.x+i.width/2,y:i.y+i.height*s}}function Rt(e,t={}){const n=t.thickness??4,i=t.idPrefix??"stage",{destinations:o,flow:r,width:s,height:a}=e,l=[];if(o.length>0){const t=o[0];if("down"===r){const r=t.y+t.height;l.push({id:i+"-floor",shape:{type:"segment",x1:e.charge.x,y1:r,x2:e.charge.x+e.charge.width,y2:r,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerX-(o[e].centerX-o[e-1].centerX)/2;l.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:s,y1:t.y,x2:s,y2:r,thickness:n}})}}else{const r=t.x+t.width;l.push({id:i+"-floor",shape:{type:"segment",x1:r,y1:e.charge.y,x2:r,y2:e.charge.y+e.charge.height,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerY-(o[e].centerY-o[e-1].centerY)/2;l.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:t.x,y1:s,x2:r,y2:s,thickness:n}})}}}return!1!==t.walls&&l.push({id:i+"-wall-left",shape:{type:"segment",x1:1,y1:0,x2:1,y2:a,thickness:n}},{id:i+"-wall-right",shape:{type:"segment",x1:s-1,y1:0,x2:s-1,y2:a,thickness:n}}),l}function Dt(e,t={}){return`${t.charge??"bodies"} enter at the ${"down"===e.flow?"top":"left"}, travel ${"down"===e.flow?"downward":"left to right"} through ${t.apparatus??"the apparatus"}, and come to rest in ${e.destinations.length} ${t.destination??"destinations"}: ${e.destinations.map(e=>e.label).join(", ")}.`}function It(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function qt(e,t,n,i){const o="function"==typeof e?e(t,n):e;return Number.isFinite(o)?Number(o):i}function Bt(e,t,n){return It(e[t])??n}function Yt(e,t){return"number"==typeof e?e:e?.[t]??0}function Wt(e){const{band:t,idPrefix:n,plot:i,projection:o}=e,{includeBoundaryWalls:r=!0,includeInteriorWalls:s=!0,wallThickness:a=4}=t,l=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const i of e.values){const o=e.scale(i);Number.isFinite(o)&&(n.add(Number(o)),n.add(Number(o)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>l.length)return[];const u=r?l.length-1:l.length-2,c=[];for(let e=r?0:1;u>=e;e+=1){if(!s&&e>0&&l.length-1>e)continue;const t=l[e];c.push({id:`${n}-wall-${e}`,shape:"x"===o?{type:"aabb",x:t,y:i.y+i.height/2,width:a,height:i.height}:{type:"aabb",x:i.x+i.width/2,y:t,width:i.width,height:a}})}return c}function Ft(e){const{plot:t,idPrefix:n="physics-scale",bounds:i={},xBins:o,xBands:r,yBands:s}=e,a=[];if(!1!==i&&a.push(...Ae(t,{idPrefix:n,...i})),o){const{idPrefix:e,yTop:i,yBottom:r,...s}=o;a.push(...Pe({...s,idPrefix:e??n+"-xbin",yTop:i??t.y,yBottom:r??t.y+t.height}))}return r&&a.push(...Wt({band:r,idPrefix:r.idPrefix??n+"-xband",plot:t,projection:"x"})),s&&a.push(...Wt({band:s,idPrefix:s.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function Tt(e){const{plot:t,rows:n,columns:i=n+1,pegRadius:o=3,idPrefix:r="galton-peg",yStart:s=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:l=!0,restitution:u=.2,friction:c=.04}=e,p=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(i));if(0===p)return[];const m=p>1?(a-s)/(p-1):0,d=t.width/h,f=[];for(let e=0;p>e;e+=1){const n=l&&e%2==1?d/2:0;for(let i=0;h>i;i+=1){const a=t.x+d*(i+.5)+n;t.x+o>a||a>t.x+t.width-o||f.push({id:`${r}-${e}-${i}`,shape:{type:"aabb",x:a,y:s+e*m,width:2*o,height:2*o},restitution:u,friction:c})}}return f}function Xt(e,t={}){const{idPrefix:n="physics-token",radius:i=5,shape:o,mass:r,vx:s,vy:a,spawnAt:l,seed:u=1,jitter:c,datum:p}=t,h=Ue(u),m=Yt(c,"x"),d=Yt(c,"y");return e.map((e,u)=>{const c=qt(t.x,e,u,Bt(e,"x",0)),f=qt(t.y,e,u,Bt(e,"y",0)),y=qt(i,e,u,5),w="function"==typeof o?o(e,u):o??{type:"circle",radius:y};return{id:`${n}-${e.index??u}`,x:c+(h()-.5)*m,y:f+(h()-.5)*d,vx:qt(s,e,u,0),vy:qt(a,e,u,0),mass:qt(r,e,u,1),spawnAt:qt(l,e,u,void 0),shape:w,datum:p?p(e,u):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function Ct(e,t={}){const{idPrefix:n="sediment",collider:i=!0,colliderThickness:o=1,restitution:r=.05,friction:s=.2,...a}=t,l=Je(e,a),u=i?l.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+o/2,width:e.width,height:o},restitution:r,friction:s})):[];return{columns:l,colliders:u}}function Lt(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:i=1,startAt:o=0,rebase:r=!0,sort:s=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return It("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),l=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:o+(r?t-l:t)})).sort((e,t)=>s?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:o,timeAccessor:"spawnAt",timeScale:i}}}var Ot=ce;export{oe as BuiltInPhysicsEngineAdapter,i as ChainReactionChart,u as CollisionSwarmChart,c as CrucibleChart,p as DEFAULT_CRUCIBLE_HEIGHT,h as DEFAULT_CRUCIBLE_OUTLETS,m as DEFAULT_CRUCIBLE_SIZE,d as DEFAULT_CRUCIBLE_WIDTH,f as EventDropChart,y as GaltonBoardChart,w as GauntletChart,g as GuantletChart,x as PacketFlowChart,b as PhysicalFlowChart,re as PhysicsCustomChart,v as PhysicsPileChart,se as PhysicsPipelineStore,ae as PhysicsSVGOverlay,le as PhysicsSedimentAccumulator,k as ProcessFlowChart,ue as StreamPhysicsFrame,M as UnitPileChart,pe as absorbRegion,he as aggregateRegionCounts,A as applyCrucibleEvent,Lt as arrivalReplay,me as bodiesToAnnotationAnchors,de as bodyGroupSpec,fe as buildCollisionSwarmPhysics,j as buildCrucibleEvidence,E as buildCrucibleInitialSpawns,S as buildCrucibleLayout,$ as buildCruciblePhysicsConfig,N as buildCrucibleProductEvents,R as buildCrucibleProjection,D as buildCrucibleStateSpawns,I as buildCrucibleTerminalSpawns,ye as buildEventDropPhysics,we as buildGaltonBoardPhysics,ge as buildPhysicalFlowPhysics,xe as buildPhysicsAnnotationContext,be as buildPhysicsPile,ve as buildProcessFlowPhysics,o as calculateBlockerAmplification,ke as capacitatedRegion,Me as chargeGateRegion,q as cloneCrucibleState,Ft as collidersFromScales,Et as comparePhysicsTrace,B as compileCruciblePlan,r as compileDependencyMachine,et as compileMotionEncoding,ct as compilePhysicsEncoding,je as composePhysicsControllers,Ve as composeStyleRules,Ee as createCapacityQueueController,Se as createDefaultPhysicsEngineAdapter,$e as createDependencyGateController,Y as createInitialCrucibleState,s as createLogicalJoin,pt as createPhysicsEncodingLayout,Ne as createPortalController,e as createProcessJourneyLedger,Re as createServiceLevelController,De as createServiceResourcePoolController,W as crucibleBondId,F as crucibleBoundaryColliders,T as crucibleComponentBodyId,X as crucibleProductBodyId,C as crucibleProjectionRows,L as crucibleSemanticKey,Ot as default,tt as deriveMotionVector,Dt as describePhysicsStageGeography,Z as evaluateCrucibleConservation,Ie as evaluatePhysicsBodyBudget,qe as forceFieldRegion,Tt as galtonPegs,Be as groupCompletionRows,st as hatchFillId,at as hatchPatternDef,lt as isHatchFill,Ke as makeRuleValueResolver,Qe as matchesThreshold,Ye as membraneRegion,We as normalizePhysicsAnnotations,nt as opacityFromAge,Nt as physicsChargePoint,$t as physicsDestination,J as physicsProcessBoundaryColliders,z as physicsProcessGroupSemanticItems,U as physicsProcessRegionSemanticItem,V as physicsProcessStageSemanticItems,kt as physicsReferenceEnvelope,Rt as physicsStageColliders,St as physicsStageGeography,K as planGauntletPropertyWork,Fe as portalRegion,Te as pressureFieldRegion,Q as processChrome,t as processJourneyRows,Xe as processLaneWalls,Ce as processStageLayout,Le as processStageRegions,Oe as processVolumePolygons,Ze as regionCountsToProjectionRows,_ as replaceGauntletNegative,ee as replayCruciblePlan,a as replayStateTransitions,te as resolveCrucibleSelector,ne as resolveCrucibleSnapshotAt,ie as resolveCrucibleTime,ht as resolveGauntletTerminalState,mt as resolveGauntletTerminalStates,it as resolveMotionAccessor,ot as resolveMotionAge,rt as resolveMotionVector,Ge as resolveStyleRules,ut as resolveSvgFill,l as routeDependencyTracks,He as routeSurfaceRegion,_e as ruleMatches,Ct as sedimentBake,Je as sedimentHeightfield,Xt as spawnFromTokens,ze as stageTargetInVolume,n as updateProcessJourney};
|
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}}var t={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},s=1e-9,i=.005;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,t,s){return Math.max(t,Math.min(s,e))}function a(e){return e<0?-1:1}function d(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 h(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 c(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function l(e,t,s,i,n,o,r,d){const h=n-e,c=(s+r)/2-Math.abs(h);if(c<=0)return null;const l=o-t,u=(i+d)/2-Math.abs(l);return u<=0?null:c<u?{nx:a(h),ny:0,penetration:c}:{nx:0,ny:a(l),penetration:u}}function u(e,t,i,n,o,a,d){const h=a/2,c=d/2;let l=e-r(e,n-h,n+h),u=t-r(t,o-c,o+c);const p=l*l+u*u;if(p>i*i)return null;if(p<=s){const s=Math.abs(e-(n-h)),r=Math.abs(e-(n+h)),a=Math.abs(t-(o-c)),d=Math.abs(t-(o+c)),p=Math.min(s,r,a,d);return p===s?(l=-1,u=0,{nx:l,ny:u,penetration:i+s}):p===r?(l=1,u=0,{nx:l,ny:u,penetration:i+r}):p===a?(l=0,u=-1,{nx:l,ny:u,penetration:i+a}):(l=0,u=1,{nx:l,ny:u,penetration:i+d})}const y=Math.sqrt(p);return{nx:l/y,ny:u/y,penetration:i-y}}function p(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,n,o,r){const a=n-e,d=o-t,h=i+r,c=a*a+d*d;if(c>=h*h)return null;if(c<=s)return{nx:1,ny:0,penetration:h};const l=Math.sqrt(c);return{nx:a/l,ny:d/l,penetration:h-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 l(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=u(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?u(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function y(e,t){const i=t.shape;if("aabb"===i.type){if("circle"===e.shape.type)return u(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height);return l(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height)}const n="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,i,n,o,a,d,h=0){const c=a-n,l=d-o,u=c*c+l*l,p=u<=s?0:r(((e-n)*c+(t-o)*l)/u,0,1),y=i+h/2,v=e-(n+c*p),m=t-(o+l*p),f=v*v+m*m;if(f>=y*y)return null;if(f<=s){const e=Math.sqrt(u);return e<=s?{nx:1,ny:0,penetration:y}:{nx:-l/e,ny:c/e,penetration:y}}const g=Math.sqrt(f);return{nx:v/g,ny:m/g,penetration:y-g}}(e.x,e.y,n,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function v(e,t){return`${e}\0${t}`}function m(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function f(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,shape:n(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function g(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 x(e){return{id:e.id,shape:o(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:g(e.bodyFilter),index:e.index}}function b(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function S(e,t){const s=e.bodyFilter;if(!s)return!0;if("function"==typeof s)return s(t);const i=function(e,t){if(!t)return;let s=e;for(const e of t.split(".")){if(null==s||"object"!=typeof s)return;s=s[e]}return s}(t,s.property);return!("equals"in s&&!Object.is(i,s.equals))&&((!("notEquals"in s)||!Object.is(i,s.notEquals))&&(!(s.oneOf&&!b(i,s.oneOf))&&(!s.notOneOf||!b(i,s.notOneOf))))}var w=class{constructor(s={}){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={...t,...s},this.random=e(this.options.seed)}init(s={}){this.options={...t,...s},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 t={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(s,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:n(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))m(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:g(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,t,s){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=s/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const s=this.sortedBodies();for(const e of s)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of s)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const s=i/t;e.vx*=s,e.vy*=s}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const n=this.bodyPairKeys(s),o=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;e<this.options.collisionIterations;e+=1)this.resolveBodyPairs(s,n,0===e),this.resolveColliders(s,o,0===e);this.updateSensors(s),this.updateSleeping(s,t)}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,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(m)}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(f),colliders:this.sortedColliders().map(x),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(t){this.options={...t.options,gravity:{...t.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(t.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of t.bodies){const t=f(e);this.bodies.set(t.id,t),this.nextBodyIndex=Math.max(this.nextBodyIndex,t.index+1)}this.nextColliderIndex=0;for(const e of t.colliders){const t=x(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of t.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 i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;const n="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,a=o*o+r*r,d=Math.sqrt(a);if(d<=s)continue;const h=o/d,c=r/d,l="vx"in n?n.vx:0,u="vy"in n?n.vy:0,p=(l-i.vx)*h+(u-i.vy)*c,y=(d-t.restLength)*t.stiffness+p*t.damping;i.vx+=y*h*e/i.mass,i.vy+=y*c*e/i.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=p(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=d(e[i]),o=Math.floor(n.minX/t),r=Math.floor(n.maxX/t),a=Math.floor(n.minY/t),h=Math.floor(n.maxY/t);for(let e=o;e<=r;e+=1)for(let t=a;t<=h;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&&(c(d(e[o]),d(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,n){e.sleeping&&this.contactOpposesGravity(n.nx,n.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-n.nx,-n.ny)&&this.supportedThisStep.add(e.id);const o=e.sleeping?0:1/e.mass,r=t.sleeping?0:1/t.mass,a=o+r;if(a<=s)return;const d=Math.max(0,n.penetration-i)/a;e.x-=n.nx*d*o,e.y-=n.ny*d*o,t.x+=n.nx*d*r,t.y+=n.ny*d*r;const h=t.vx-e.vx,c=t.vy-e.vy,l=h*n.nx+c*n.ny;if(l>0)return;const u=Math.abs(l),p=-(1+Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution))*l/a,y=p*n.nx,v=p*n.ny;e.vx-=y*o,e.vy-=v*o,t.vx+=y*r,t.vy+=v*r,this.applyFriction(e,t,n,p,o,r),u>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,n,o,a){const d=-i.ny,h=i.nx,c=(t.vx-e.vx)*d+(t.vy-e.vy)*h,l=o+a;if(Math.abs(c)<=s||l<=s)return;const u=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction))),p=r(-c/l,-n*u,n*u),y=p*d,v=p*h;e.vx-=y*o,e.vy-=v*o,t.vx+=y*a,t.vy+=v*a}resolveColliders(e,t,s){for(const i of e)for(const e of t){if(!S(e,i))continue;if(!c(d(i),h(e)))continue;const t=y(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,t,s){e.x+=s.nx*Math.max(0,s.penetration-i),e.y+=s.ny*Math.max(0,s.penetration-i);const n=e.vx*s.nx+e.vy*s.ny;if(n<0){const i=Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution);e.vx-=(1+i)*n*s.nx,e.vy-=(1+i)*n*s.ny;const o=-s.ny,r=s.nx,a=e.vx*o+e.vy*r,d=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction)));e.vx-=a*o*d,e.vy-=a*r*d}}updateSensors(e){const t=new Set,s=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=d(i);for(const n of s){if(!S(n,i))continue;if(!c(e,h(n)))continue;if(!y(i,n))continue;const s=v(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}=m(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()}},I=class{constructor(e={}){this.id="builtin",this.capabilities={...(new w).capabilities,engine:"builtin"},this.world=new w(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 B(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new I(e)}(t)}var M=["binId","targetBin","category","windowIndex","lane","group"];function O(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function q(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 k(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 T(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 C(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 A(e,t,s){return"function"==typeof e?e(t,s):"string"==typeof e?C(t,e):void 0}function D(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function R(e){const t=k(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:k(e.x),y:k(e.y),value:t}}var E=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=D(A(this.config.binAccessor,e,t))??function(e){for(const t of M){const s=D(C(e,t));if(s)return s}return"sediment"}(e),i=D(A(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?C(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:O(),y:O(),value:O()},this.bins.set(s,r)),r.label=i,r.lastBodyId=e.id,r.lastDatum=e.datum,q(r.x,e.x),q(r.y,e.y),q(r.value,n),o>0&&(r.bodyIds.push(e.id),r.bodyIds.length>o&&(r.bodyIds=r.bodyIds.slice(r.bodyIds.length-o))),R(r)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(R)}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:T(t.x),y:T(t.y),value:T(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 N(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function P(e){const t=Math.max(0,Math.floor(e.liveBodies)),s=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+s,n=N(e.bodyLimit),o=N(e.engineMaxBodiesHint),r=function(e,t,s){if(!1===s)return;const i=N(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 F={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Y={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function X(e={},t=Y){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 L(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function K(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 H(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 j(e,t={}){const s=K(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,s)=>function(e,t,s){return"function"==typeof s?K(s(e,t)):"string"==typeof s?K(H(e,s)):K(e.spawnAt)??K(H(e,"arrivalTime"))??K(H(e,"timestamp"))??K(H(e,"time"))??K(H(e,"eventTime"))}(e,s,t.timeAccessor)),n=i.filter(e=>null!=e),o=n.length>0?Math.min(...n):0,r=K(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{...L(e),spawnAt:s+r/a}})}if("object"==typeof i){const t=K(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...L(e),spawnAt:s+i/t}))}return e.map(e=>({...L(e),spawnAt:s}))}function V(e){return{...L(e),sequence:e.sequence,spawnAt:e.spawnAt}}function $(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 z(e){return!1!==e&&{...e}}function W(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function G(e){return{...e,gravity:{...e.gravity}}}function _(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 U(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}var Q={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 J(e,t){const s={...e};for(const e of t){s[Q[e]]++}return s}function Z(e,t,s){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:J(s,i)}}var ee=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=Z({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=Z(e,t,this.revisions);this.revisions=s.revisions,this.latest=s;for(const e of[...this.listeners])e();return s}};import{quadtree as te}from"d3-quadtree";var se=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,s,i,n,o=0){const r=this.ensure(e,t);if(!r)return null;let a=null,d=Number.POSITIVE_INFINITY;const h=Math.max(0,o)+this.maxSearchRadius,c=i-h,l=i+h,u=n-h,p=n+h;return r.visit((e,t,r,h,y)=>{if(h<c||t>l||y<u||r>p)return!0;if(e.length)return!1;let v=e;for(;v;){const e=v.data;if(e){const t=_(e,i,n,Math.max(0,o));null!=t&&(t<d||t===d&&s.indexOf(e.id)>s.indexOf(a?.id??""))&&(a=e,d=t)}v=v.next}return!1}),a}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=te().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};var ie=["data","scene-geometry","data-paint","accessibility","evidence"],ne=["scene-geometry","data-paint","accessibility","evidence"],oe=["overlay","accessibility","evidence"],re=(e,t)=>({retainedData:e,invalidations:t}),ae=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],de=["scene-geometry","data-paint","accessibility","evidence"],he=[],ce={engine:re("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:re("preserve",de),colliders:re("preserve",de),sediment:re("preserve",de),bodyBudget:re("preserve",ae),bodyLimit:re("preserve",ae),eviction:re("preserve",ae),fixedDt:re("preserve",he),maxDeltaSeconds:re("preserve",he),maxSubsteps:re("preserve",he),settleStepLimit:re("preserve",he),timeScale:re("preserve",he),observation:re("preserve",he)},le=re("preserve",ae);function ue(e){let t="preserve";const s=new Set;for(const i of e){const e=ce[i]??le;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)s.add(t)}return{retainedData:t,invalidations:s}}var pe=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function ye(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&pe.every(s=>e[s]===t[s]))}function ve(e,t,s,i){return e||!t?"paused":s||!i?"running":"settled"}function me(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 fe=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}};var ge=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new se,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new ee,this.simulationState="settled",this.visible=!0,this.quiescence=new fe;const{bodyBudget:t,colliders:s,engine:i,kernel:n,observation:o,sediment:r,...a}=e;this.config={...F,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=X(o),this.sediment=new E(r??!1),this.world=B(i,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),s&&this.world.setColliders($(s))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(s=>"kernel"===s?!ye(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=B(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!ye(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=X(r,this.observation)),this.sediment.updateConfig(a),s&&(this.world.setColliders($(s)),this.revision+=1),this.configInput={...this.configInput,...e};const h=ue(t);this.updateResults.record({kind:"config",keys:t},h.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders($(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ue(["colliders"]).invalidations)}enqueue(e,t){const s=Array.isArray(e)?e:[e],i=t?j(s,{...t,startAt:t.startAt??this.elapsedSeconds}):s;for(const e of i)this.queue.push({...L(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(W),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?ie:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(L(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},ie)}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?ie:[])),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"},ie)}tick(e){const t=this.revision,s=[],i=[],n=[],o=[],r=[];if(this.paused||!this.visible){const e=this.result(0,s,i,n,o,r,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(s,r);const d=this.observeBodyBudget(r),h=this.evictOverflow(r);i.push(...h.evicted),n.push(...h.sedimented),this.syncSimulationState(r),this.accumulator+=a;let c=0;for(;this.accumulator>=this.config.fixedDt&&c<this.config.maxSubsteps;){this.world.step(this.config.fixedDt);const e=this.world.events();o.push(...e),this.observeKernelEvents(e,r),this.observeSensorTransitions(r),this.accumulator-=this.config.fixedDt,c+=1}c===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,s.length),(c>0||s.length>0||i.length>0||n.length>0||o.length>0)&&(this.revision+=1);const l=this.result(c,s,i,n,o,r,void 0,d);return this.updateResults.record({kind:"tick",count:c},this.revision!==t?s.length||i.length||n.length?ie:ne:[]),l}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit){return this.runSettle(e,!0)}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){const s=this.revision,i=[],n=[],o=[],r=[],a=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,i,n,o,r,a??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(i,a);const d=this.observeBodyBudget(a),h=this.evictOverflow(a);n.push(...h.evicted),o.push(...h.sedimented),this.syncSimulationState(a),i.length>0&&this.quiescence.reset();const c=t?{spawned:i,evicted:n,sedimented:o,events:r,observations:a}:{spawned:i},{steps:l,budget:u}=function(e,t,s){let i,n=0;for(;n<t&&(e.queueSize()>0||!e.atRest());){e.advanceTime(e.fixedDt);const t=[];if(e.spawnDue(t,s.observations),t.length>0){s.spawned.push(...t),i=e.observeBodyBudget(s.observations);const n=e.evictOverflow(s.observations);s.evicted?.push(...n.evicted),s.sedimented?.push(...n.sedimented)}e.step(e.fixedDt);const o=e.drainEvents();s.events&&(s.events.push(...o),e.observeKernelEvents(o,s.observations),e.observeSensorTransitions(s.observations)),n+=1,e.refreshQuiescence(e.fixedDt,t.length)}return{steps:n,budget:i}}(this.settleHost(),e,c),p=i.length+n.length+o.length>0;(l>0||p||r.length>0)&&(this.revision+=1);const y=this.result(l,i,n,o,r,a??[],void 0,u??d);return this.updateResults.record({kind:"settle",count:l},this.revision===s?[]:p?ie:ne),y}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){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,s)}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?oe:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?oe:[])}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?ie:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},ne),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},ne)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},ne)}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:z(this.bodyBudget),config:{...this.config,kernel:G(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(V),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){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:z(e.bodyBudget??{}),kernel:G(e.world.options)},this.bodyBudget=z(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(V).sort(W),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??ve(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"},ie)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds;){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.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}=U(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(U(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 P({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,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=ve(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}=me(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 xe(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 be(e){return xe(e,e.tick(0))}var Se=function(){let e=new ge;return{handle(t){switch(t.type){case"init":return e=new ge(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:be(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:be(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:be(e)};case"tick":return{type:"frame",frame:xe(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:xe(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:be(e)};case"clear":return e.clear(),{type:"frame",frame:be(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:be(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:be(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:be(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:be(e)}}}}}();function we(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=Se.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:we(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}}var t={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},s=1e-9,i=.005;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,t,s){return Math.max(t,Math.min(s,e))}function a(e,t,s){return Math.min(e??s,t??s)}function d(e,t,s){return r(Math.max(e??s,t??s),0,1)}function h(e){return e<0?-1:1}function c(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 l(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 u(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function p(e,t,s,i,n,o,r,a){const d=n-e,c=(s+r)/2-Math.abs(d);if(c<=0)return null;const l=o-t,u=(i+a)/2-Math.abs(l);return u<=0?null:c<u?{nx:h(d),ny:0,penetration:c}:{nx:0,ny:h(l),penetration:u}}function y(e,t,i,n,o,a,d){const h=a/2,c=d/2,l=e-r(e,n-h,n+h),u=t-r(t,o-c,o+c),p=l*l+u*u;if(p>i*i)return null;if(p<=s){const s=Math.abs(e-(n-h)),r=Math.abs(e-(n+h)),a=Math.abs(t-(o-c)),d=Math.abs(t-(o+c)),l=Math.min(s,r,a,d);return l===s?{nx:-1,ny:0,penetration:i+s}:l===r?{nx:1,ny:0,penetration:i+r}:l===a?{nx:0,ny:-1,penetration:i+a}:{nx:0,ny:1,penetration:i+d}}const y=Math.sqrt(p);return{nx:l/y,ny:u/y,penetration:i-y}}function v(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,n,o,r){const a=n-e,d=o-t,h=i+r,c=a*a+d*d;if(c>=h*h)return null;if(c<=s)return{nx:1,ny:0,penetration:h};const l=Math.sqrt(c);return{nx:a/l,ny:d/l,penetration:h-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 p(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=y(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?y(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function m(e,t){const i=t.shape;if("aabb"===i.type)return"circle"===e.shape.type?y(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height):p(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height);const n="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,i,n,o,a,d,h=0){const c=a-n,l=d-o,u=c*c+l*l,p=u<=s?0:r(((e-n)*c+(t-o)*l)/u,0,1),y=i+h/2,v=e-(n+c*p),m=t-(o+l*p),f=v*v+m*m;if(f>=y*y)return null;if(f<=s){const e=Math.sqrt(u);return e<=s?{nx:1,ny:0,penetration:y}:{nx:-l/e,ny:c/e,penetration:y}}const g=Math.sqrt(f);return{nx:v/g,ny:m/g,penetration:y-g}}(e.x,e.y,n,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function f(e,t){return`${e}\0${t}`}function g(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function x(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,shape:n(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function b(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 S(e){return{id:e.id,shape:o(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:b(e.bodyFilter),index:e.index}}function w(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function I(e,t){return function(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;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&&!w(s,t.oneOf)||t.notOneOf&&w(s,t.notOneOf))}(t,e.bodyFilter)}var B=class{constructor(s={}){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={...t,...s},this.random=e(this.options.seed)}init(s={}){this.options={...t,...s},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 t={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(s,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:n(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))g(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:b(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,t,s){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=s/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const s=this.sortedBodies();for(const e of s)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of s)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const s=i/t;e.vx*=s,e.vy*=s}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const n=this.bodyPairKeys(s),o=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;e<this.options.collisionIterations;e+=1)this.resolveBodyPairs(s,n,0===e),this.resolveColliders(s,o,0===e);this.updateSensors(s),this.updateSleeping(s,t)}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,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(g)}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(x),colliders:this.sortedColliders().map(S),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(t){this.options={...t.options,gravity:{...t.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(t.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of t.bodies){const t=x(e);this.bodies.set(t.id,t),this.nextBodyIndex=Math.max(this.nextBodyIndex,t.index+1)}this.nextColliderIndex=0;for(const e of t.colliders){const t=S(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of t.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 i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;const n="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,a=o*o+r*r,d=Math.sqrt(a);if(d<=s)continue;const h=o/d,c=r/d,l="vx"in n?n.vx:0,u="vy"in n?n.vy:0,p=(l-i.vx)*h+(u-i.vy)*c,y=(d-t.restLength)*t.stiffness+p*t.damping;i.vx+=y*h*e/i.mass,i.vy+=y*c*e/i.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=v(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=c(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&&(u(c(e[o]),c(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,n){e.sleeping&&this.contactOpposesGravity(n.nx,n.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-n.nx,-n.ny)&&this.supportedThisStep.add(e.id);const o=e.sleeping?0:1/e.mass,r=t.sleeping?0:1/t.mass,d=o+r;if(d<=s)return;const h=Math.max(0,n.penetration-i)/d;e.x-=n.nx*h*o,e.y-=n.ny*h*o,t.x+=n.nx*h*r,t.y+=n.ny*h*r;const c=t.vx-e.vx,l=t.vy-e.vy,u=c*n.nx+l*n.ny;if(u>0)return;const p=Math.abs(u),y=-(1+a(e.restitution,t.restitution,this.options.restitution))*u/d,v=y*n.nx,m=y*n.ny;e.vx-=v*o,e.vy-=m*o,t.vx+=v*r,t.vy+=m*r,this.applyFriction(e,t,n,y,o,r),p>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,n,o,a){const h=-i.ny,c=i.nx,l=(t.vx-e.vx)*h+(t.vy-e.vy)*c,u=o+a;if(Math.abs(l)<=s||u<=s)return;const p=d(e.friction,t.friction,this.options.friction),y=r(-l/u,-n*p,n*p),v=y*h,m=y*c;e.vx-=v*o,e.vy-=m*o,t.vx+=v*a,t.vy+=m*a}resolveColliders(e,t,s){for(const i of e)for(const e of t){if(!I(e,i))continue;if(!u(c(i),l(e)))continue;const t=m(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,t,s){e.x+=s.nx*Math.max(0,s.penetration-i),e.y+=s.ny*Math.max(0,s.penetration-i);const n=e.vx*s.nx+e.vy*s.ny;if(n<0){const i=a(e.restitution,t.restitution,this.options.restitution);e.vx-=(1+i)*n*s.nx,e.vy-=(1+i)*n*s.ny;const o=-s.ny,r=s.nx,h=e.vx*o+e.vy*r,c=d(e.friction,t.friction,this.options.friction);e.vx-=h*o*c,e.vy-=h*r*c}}updateSensors(e){const t=new Set,s=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=c(i);for(const n of s){if(!I(n,i))continue;if(!u(e,l(n)))continue;if(!m(i,n))continue;const s=f(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}=g(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()}},M=class{constructor(e={}){this.id="builtin",this.capabilities={...(new B).capabilities,engine:"builtin"},this.world=new B(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 O(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new M(e)}(t)}var q=["binId","targetBin","category","windowIndex","lane","group"];function k(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function T(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 C(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 A(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 D(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 R(e,t,s){return"function"==typeof e?e(t,s):"string"==typeof e?D(t,e):void 0}function E(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function N(e){const t=C(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:C(e.x),y:C(e.y),value:t}}var P=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=E(R(this.config.binAccessor,e,t))??function(e){for(const t of q){const s=E(D(e,t));if(s)return s}return"sediment"}(e),i=E(R(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?D(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:k(),y:k(),value:k()},this.bins.set(s,r)),r.label=i,r.lastBodyId=e.id,r.lastDatum=e.datum,T(r.x,e.x),T(r.y,e.y),T(r.value,n),o>0&&(r.bodyIds.push(e.id),r.bodyIds.length>o&&(r.bodyIds=r.bodyIds.slice(r.bodyIds.length-o))),N(r)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(N)}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:A(t.x),y:A(t.y),value:A(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 F(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function Y(e){const t=Math.max(0,Math.floor(e.liveBodies)),s=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+s,n=F(e.bodyLimit),o=F(e.engineMaxBodiesHint),r=function(e,t,s){if(!1===s)return;const i=F(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 X={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},L={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function K(e={},t=L){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 H(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function j(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 V(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=j(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,s)=>function(e,t,s){return"function"==typeof s?j(s(e,t)):"string"==typeof s?j(V(e,s)):j(e.spawnAt)??j(V(e,"arrivalTime"))??j(V(e,"timestamp"))??j(V(e,"time"))??j(V(e,"eventTime"))}(e,s,t.timeAccessor)),n=i.filter(e=>null!=e),o=n.length>0?Math.min(...n):0,r=j(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{...H(e),spawnAt:s+r/a}})}if("object"==typeof i){const t=j(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...H(e),spawnAt:s+i/t}))}return e.map(e=>({...H(e),spawnAt:s}))}function z(e){return{...H(e),sequence:e.sequence,spawnAt:e.spawnAt}}function W(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 G(e){return!1!==e&&{...e}}function _(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function U(e){return{...e,gravity:{...e.gravity}}}function Q(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 J(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}var Z={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 ee(e,t){const s={...e};for(const e of t){s[Z[e]]++}return s}function te(e,t,s){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:ee(s,i)}}var se=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=te({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=te(e,t,this.revisions);this.revisions=s.revisions,this.latest=s;for(const e of[...this.listeners])e();return s}};import{quadtree as ie}from"d3-quadtree";var ne=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,s,i,n,o=0){const r=this.ensure(e,t);if(!r)return null;let a=null,d=Number.POSITIVE_INFINITY;const h=Math.max(0,o)+this.maxSearchRadius,c=i-h,l=i+h,u=n-h,p=n+h;return r.visit((e,t,r,h,y)=>{if(h<c||t>l||y<u||r>p)return!0;if(e.length)return!1;let v=e;for(;v;){const e=v.data;if(e){const t=Q(e,i,n,Math.max(0,o));null!=t&&(t<d||t===d&&s.indexOf(e.id)>s.indexOf(a?.id??""))&&(a=e,d=t)}v=v.next}return!1}),a}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=ie().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};var oe=["data","scene-geometry","data-paint","accessibility","evidence"],re=["scene-geometry","data-paint","accessibility","evidence"],ae=["overlay","accessibility","evidence"],de=(e,t)=>({retainedData:e,invalidations:t}),he=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],ce=["scene-geometry","data-paint","accessibility","evidence"],le=[],ue={engine:de("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:de("preserve",ce),colliders:de("preserve",ce),sediment:de("preserve",ce),bodyBudget:de("preserve",he),bodyLimit:de("preserve",he),eviction:de("preserve",he),fixedDt:de("preserve",le),maxDeltaSeconds:de("preserve",le),maxSubsteps:de("preserve",le),settleStepLimit:de("preserve",le),timeScale:de("preserve",le),observation:de("preserve",le)},pe=de("preserve",he);function ye(e){let t="preserve";const s=new Set;for(const i of e){const e=ue[i]??pe;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)s.add(t)}return{retainedData:t,invalidations:s}}var ve=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function me(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&ve.every(s=>e[s]===t[s]))}function fe(e,t,s,i){return e||!t?"paused":s||!i?"running":"settled"}function ge(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 xe=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}};var be=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new ne,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new se,this.simulationState="settled",this.visible=!0,this.quiescence=new xe;const{bodyBudget:t,colliders:s,engine:i,kernel:n,observation:o,sediment:r,...a}=e;this.config={...X,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=K(o),this.sediment=new P(r??!1),this.world=O(i,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),s&&this.world.setColliders(W(s))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(s=>"kernel"===s?!me(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=O(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!me(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=K(r,this.observation)),this.sediment.updateConfig(a),s&&(this.world.setColliders(W(s)),this.revision+=1),this.configInput={...this.configInput,...e};const h=ye(t);this.updateResults.record({kind:"config",keys:t},h.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(W(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ye(["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({...H(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(_),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?oe:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(H(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},oe)}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?oe:[])),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"},oe)}tick(e){const t=this.revision,s=[],i=[],n=[],o=[],r=[];if(this.paused||!this.visible){const e=this.result(0,s,i,n,o,r,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(s,r);const d=this.observeBodyBudget(r),h=this.evictOverflow(r);i.push(...h.evicted),n.push(...h.sedimented),this.syncSimulationState(r),this.accumulator+=a;let c=0;for(;this.accumulator>=this.config.fixedDt&&c<this.config.maxSubsteps;){this.world.step(this.config.fixedDt);const e=this.world.events();o.push(...e),this.observeKernelEvents(e,r),this.observeSensorTransitions(r),this.accumulator-=this.config.fixedDt,c+=1}c===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,s.length),(c>0||s.length>0||i.length>0||n.length>0||o.length>0)&&(this.revision+=1);const l=this.result(c,s,i,n,o,r,void 0,d);return this.updateResults.record({kind:"tick",count:c},this.revision!==t?s.length||i.length||n.length?oe:re:[]),l}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit){return this.runSettle(e,!0)}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){const s=this.revision,i=[],n=[],o=[],r=[],a=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,i,n,o,r,a??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(i,a);const d=this.observeBodyBudget(a),h=this.evictOverflow(a);n.push(...h.evicted),o.push(...h.sedimented),this.syncSimulationState(a),i.length>0&&this.quiescence.reset();const c=t?{spawned:i,evicted:n,sedimented:o,events:r,observations:a}:{spawned:i},{steps:l,budget:u}=function(e,t,s){let i,n=0;for(;n<t&&(e.queueSize()>0||!e.atRest());){e.advanceTime(e.fixedDt);const t=[];if(e.spawnDue(t,s.observations),t.length>0){s.spawned.push(...t),i=e.observeBodyBudget(s.observations);const n=e.evictOverflow(s.observations);s.evicted?.push(...n.evicted),s.sedimented?.push(...n.sedimented)}e.step(e.fixedDt);const o=e.drainEvents();s.events&&(s.events.push(...o),e.observeKernelEvents(o,s.observations),e.observeSensorTransitions(s.observations)),n+=1,e.refreshQuiescence(e.fixedDt,t.length)}return{steps:n,budget:i}}(this.settleHost(),e,c),p=i.length+n.length+o.length>0;(l>0||p||r.length>0)&&(this.revision+=1);const y=this.result(l,i,n,o,r,a??[],void 0,u??d);return this.updateResults.record({kind:"settle",count:l},this.revision===s?[]:p?oe:re),y}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){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,s)}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?ae:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?ae:[])}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?oe:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},re),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},re)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},re)}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:G(this.bodyBudget),config:{...this.config,kernel:U(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(z),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){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:G(e.bodyBudget??{}),kernel:U(e.world.options)},this.bodyBudget=G(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(z).sort(_),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??fe(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"},oe)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds;){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.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}=J(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(J(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 Y({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,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=fe(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}=ge(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 Se(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 we(e){return Se(e,e.tick(0))}var Ie=function(){let e=new be;return{handle(t){switch(t.type){case"init":return e=new be(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:we(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:we(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:we(e)};case"tick":return{type:"frame",frame:Se(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:Se(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:we(e)};case"clear":return e.clear(),{type:"frame",frame:we(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:we(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:we(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:we(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:we(e)}}}}}();function Be(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=Ie.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:Be(e),ok:!1,requestId:t.requestId})}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{scaleTime as t}from"d3-scale";var e={static:{duplicateIds:"fatal",invalidSystemTime:"warn"},mcp:{duplicateIds:"fatal",invalidSystemTime:"warn"},push:{duplicateIds:"warn",invalidSystemTime:"strip"}};function n(t="static"){return e[t]??e.static}var o=new Set(["invalid-domain","missing-node","backward-edge","invalid-edge-time","invalid-value","invalid-node-time"]);function s(t){return"fatal"===t.severity||"warn"===t.severity?t.severity:o.has(t.kind)?"fatal":"warn"}function i(t){const{desired:e,minGaps:n,weights:o}=t,s=e.length;if(0===s)return[];if(n.length!==Math.max(0,s-1))throw new Error("placeWithMinGap: minGaps must have desired.length - 1 entries");const i=new Array(s).fill(0);for(let t=1;t<s;t++)i[t]=i[t-1]+Math.max(0,Number.isFinite(n[t-1])?n[t-1]:0);const a=[];for(let t=0;t<s;t++){const n=Math.max(Number.EPSILON,Number.isFinite(o?.[t])?o[t]:1),s=(Number.isFinite(e[t])?e[t]:0)-i[t];for(a.push({start:t,end:t,weight:n,mean:s});a.length>1;){const t=a[a.length-1],e=a[a.length-2];if(e.mean<=t.mean)break;const n=e.weight+t.weight;a.splice(a.length-2,2,{start:e.start,end:t.end,weight:n,mean:(e.mean*e.weight+t.mean*t.weight)/n})}}const r=Number.isFinite(t.min)?t.min:-1/0,l=Number.isFinite(t.max)?t.max-i[s-1]:1/0,c=l<r?r:l,u=new Array(s);for(const t of a){const e=Math.max(r,Math.min(c,t.mean));for(let n=t.start;n<=t.end;n++)u[n]=e+i[n]}return u}function a(t,e){let n=0,o=t.length-1,s=-1;for(;n<=o;){const i=n+o>>>1;t[i].at<=e?(s=i,n=i+1):o=i-1}return s<0?{at:e,before:0,after:0}:t[s]}function r(t,e=0){if(0===t.length)return{adjacentClearance:[],positions:[]};const n=[],o=[0];for(let s=0;s<t.length-1;s++){const i=t[s],r=t[s+1],l=[...new Set([...i.map(t=>t.at),...r.map(t=>t.at)])].sort((t,e)=>t-e);let c=0;for(const t of l){const e=a(i,t),n=a(r,t);c=Math.max(c,e.after+n.before)}n.push(c),o.push(o[o.length-1]+c+e)}return{adjacentClearance:n,positions:o}}function l(t,e,n,o={}){let s=[...t];if(s.length<=1)return s;let i=[...s],a=n(s),r=1;const l=Math.max(0,o.passes??6),c=Math.max(1,o.maxEvaluations??1/0);for(let t=0;t<l&&r<c;t++){const t=new Map(s.map((t,e)=>[t,e])),l=new Map,c=new Map;for(const n of e){const e=t.get(n.source),o=t.get(n.target);if(null==e||null==o)continue;const s=Number.isFinite(n.weight)&&n.weight>0?n.weight:1;l.set(n.source,(l.get(n.source)??0)+o*s),c.set(n.source,(c.get(n.source)??0)+s),l.set(n.target,(l.get(n.target)??0)+e*s),c.set(n.target,(c.get(n.target)??0)+s)}s=s.map((t,e)=>({item:t,index:e,barycenter:(l.get(t)??e)/(c.get(t)??1)})).sort((t,e)=>t.barycenter-e.barycenter||(o.compare?.(t.item,e.item)??t.index-e.index)).map(t=>t.item);const u=n(s);if(r++,u<a)a=u,i=[...s];else if(u===a)break}return i}function c(t,e,n={}){const o=[...t],s=o.length;if(s<=1||s>(n.maxItems??8))return o;const i=Math.max(1,n.maxEvaluations??1/0);let a=0,r=[...o],l=1/0;const c=()=>{if(a>=i)return;const t=e(o);a++,t<l&&(l=t,r=[...o])};c();const u=new Array(s).fill(0);let f=0;for(;f<s&&a<i;)if(u[f]<f){const t=f%2==0?0:u[f];[o[t],o[f]]=[o[f],o[t]],c(),u[f]++,f=0}else u[f]=0,f++;return r}function u(t,e){return t<e?-1:t>e?1:0}function f(t){return t.occupants.map(t=>t.id).sort(u).join("\0")}function d(t,e,n=0){return t.slice(0,-1).map((o,s)=>{const i=t[s+1];return null!=o.group&&o.group===i.group?n:e})}function g(t,e){return t.map(t=>{const n=new Map;for(const o of t.occupants){const t=e[o.id];if(t)for(const e of t.samples){const t=n.get(e.t)??{before:0,after:0},o=e.boundaryOffset??0;n.set(e.t,{before:Math.max(t.before,e.topMass-o),after:Math.max(t.after,e.botMass+o)})}}return[...n].sort((t,e)=>t[0]-e[0]).map(([t,e])=>({at:t,...e}))})}function m(t,e,n){if(0===t.length)return[];const{padding:o,plotH:s,valueScale:i}=n,a=n.stackValueScale??i,r=d(t,o,n.groupPadding??0),l=[o+t[0].peak.topPeak*a];for(let n=1;n<t.length;n++)l.push(l[n-1]+e[n-1]*a+r[n-1]);const c=l[l.length-1]+t[t.length-1].peak.botPeak*a+o;if(c>s&&c>0){const t=s/c;for(let e=0;e<l.length;e++)l[e]*=t}return l}function p(t,e){const n=(t.boundaryOffset??0)*e,o=t.value*e;if("out"===t.kind){const s=t.sideMassBefore*e;return n+("top"===t.side?o/2-s:s-o/2)}const s=t.sideMassAfter*e;return n+("top"===t.side?o/2-s:s-o/2)}function h(t,e,n,o,s,a){const l=a.adjacentClearance?[...a.adjacentClearance]:r(g(o,n)).adjacentClearance,c=m(o,l,a);let u="hug"===a.lanePlacement?function(t,e,n,o,s,a,r){const l=t.length;if(0===l)return[];const{padding:c,plotH:u,valueScale:f}=r,g=d(t,c,r.groupPadding??0),h=s.map((t,e)=>t*f+g[e]),b=c+t[0].peak.topPeak*f,M=u-c-t[l-1].peak.botPeak*f;if(M-b<=h.reduce((t,e)=>t+e,0)+1e-6)return m(t,s,r);let y=1===l?[(b+M)/2]:[...a];for(let t=0;t<12;t++){const t=new Array(l).fill(0),s=new Array(l).fill(0);for(const i of n){const n=e[i.source],a=e[i.target];if(null==n||null==a||n===a)continue;const r=o[i.source]?.localAttachments.get(i.id),l=o[i.target]?.localAttachments.get(i.id);if(!r||!l)continue;const c=i.value>0&&Number.isFinite(i.value)?i.value:1,u=p(r,f),d=p(l,f);t[n]+=(y[a]+d-u)*c,s[n]+=c,t[a]+=(y[n]+u-d)*c,s[a]+=c}const a=i({desired:y.map((e,n)=>0===s[n]?e:.45*e+t[n]/s[n]*.55),minGaps:h,weights:s.map(t=>Math.max(1,t)),min:b,max:M});let r=0;for(let t=0;t<l;t++)r=Math.max(r,Math.abs(a[t]-y[t]));if(y=a,r<.01)break}return y}(o,s,e,n,l,c,a):[...c];if("hug"===a.lanePlacement){const n=e=>{const n={};for(const o of t)n[o.id]=e[s[o.id]];return n};b(n(u),e)>b(n(c),e)+1e-6&&(u=[...c])}const f={};for(const e of t)f[e.id]=u[s[e.id]];let h=1/0,M=-1/0;for(const e of t){const t=f[e.id],o=n[e.id];Number.isFinite(t)&&o&&(h=Math.min(h,t-o.topPeak*a.valueScale),M=Math.max(M,t+o.botPeak*a.valueScale))}return{adjacentClearance:l,centerlines:f,slotCenter:u,stackCenter:c,verticalUtilization:Number.isFinite(h)&&Number.isFinite(M)&&a.plotH>0?Math.max(0,Math.min(1,(M-h)/a.plotH)):0}}function b(t,e){let n=0;for(const o of e){const e=t[o.source],s=t[o.target];Number.isFinite(e)&&Number.isFinite(s)&&(n+=Math.abs(e-s)*(o.value>0?o.value:1))}return n}function M(t,e){const n=t?.samples;if(!n||0===n.length||e<n[0].t)return{top:0,bot:0};let o=0,s=n.length-1,i=0;for(;o<=s;){const t=o+s>>>1;n[t].t<=e?(i=t,o=t+1):s=t-1}const a=n[i].boundaryOffset??0;return{top:n[i].topMass-a,bot:n[i].botMass+a}}function y(t,e,n,o,s){const i=1-s;return i*i*i*t+3*i*i*s*e+3*i*s*s*n+s*s*s*o}function x(t,e){let n=0,o=1;for(let s=0;s<28;s++){const s=(n+o)/2;y(0,e,e,1,s)<t?n=s:o=s}return(n+o)/2}function w(t,e,n){const o=e+p(t,n),s=t.value*n/2;return[o-s,o+s]}function v(t,e,n,o){return Math.max(0,Math.min(e,o)-Math.max(t,n))/Math.max(1e-9,e-t)}function k(t,e,n,o,s,i,a){const{valueScale:r,domain:l,mode:c="quality"}=a,u="source"===a.ribbonLane?.85:"target"===a.ribbonLane?.15:.5;let f=0;for(const a of t){const t=o[a.source],d=o[a.target];if(null==t||null==d||Math.abs(t-d)<2)continue;const g=e[a.source]?.localAttachments.get(a.id),m=e[a.target]?.localAttachments.get(a.id);if(!g||!m)continue;const p=Math.max(a.startTime,l?.[0]??-1/0),h=Math.min(a.endTime,l?.[1]??1/0);if(!(h>p))continue;const[b,k]=w(g,s[a.source],r),[T,S]=w(m,s[a.target],r),N=Math.min(t,d)+1,O=Math.max(t,d)-1;for(let t=N;t<=O;t++){const o=n[t];if(!o)continue;const l=[p,h];if("quality"===c)for(const t of o.occupants)for(const n of e[t.id]?.samples??[])n.t>p&&n.t<h&&l.push(n.t);const d=t=>{const n=x((t-p)/(h-p),u),l=y(b,b,T,T,n),c=y(k,k,S,S,n);let f=0;for(const n of o.occupants){if(n.id===a.source||n.id===a.target)continue;const o=i[n.id];if(null!=o?.start&&t<o.start)continue;if(null!=o?.end&&t>o.end)continue;const u=M(e[n.id],t),d=s[n.id];f=Math.max(f,v(l,c,d-u.top*r,d+u.bot*r))}return f},g=[...new Set(l)].sort((t,e)=>t-e);let m=0;for(let t=0;t<g.length-1;t++){const e=g[t],n=g[t+1]-e;m+=(d(e+.25*n)+d(e+.5*n)+d(e+.75*n))/3*n}f+=m/(h-p)*(a.value>0?a.value:1)}}return f}function T(t,e,n,o,s,i,a,r,l,c,u="both",f){return{crossings:t,weightedLength:e,pixelLength:b(a,n),transitOcclusion:k(n,o,s,i,a,r,{valueScale:l,ribbonLane:u,domain:f,mode:"quality"}),verticalUtilization:c}}function S(t,e){return e?Math.max(e[0],Math.min(e[1],t)):t}function N(t,e){return t.map(t=>({t:S(t.t,e),topMass:t.topMass,botMass:t.botMass,...null!=t.boundaryOffset&&{boundaryOffset:t.boundaryOffset}}))}function O(t,e,n){const o=e+(t.boundaryOffset??0)*n,s=t.value*n;if("out"===t.kind){const e=t.sideMassBefore*n;if("top"===t.side){const t=o-e;return[t,t+s]}const i=o+e;return[i-s,i]}const i=t.sideMassAfter*n;if("top"===t.side){const t=o-i;return[t,t+s]}const a=o+i;return[a-s,a]}function P(t,e,n,o,s="temporal"){const i=e.incoming[t.id],a=e.outgoing[t.id],r=[];for(const t of i)r.push({time:t.endTime,delta:+t.value,edge:t,kind:"in",side:n.get(t.id).targetSide});for(const t of a)r.push({time:t.startTime,delta:-t.value,edge:t,kind:"out",side:n.get(t.id).sourceSide});const l={create:0,in:1,"transfer-out":2,"transfer-in":3,out:4},c=()=>{r.sort((t,e)=>t.time-e.time||(t.phase??0)-(e.phase??0)||(t.sequence??0)-(e.sequence??0)||(l[t.kind]??99)-(l[e.kind]??99)||((t,e)=>{if(!o||!t.edge||!e.edge||t.kind!==e.kind||t.side!==e.side)return 0;if("out"===t.kind){if(t.edge.target===e.edge.target&&t.edge.endTime===e.edge.endTime)return 0;const n=o.get(t.edge.id)?.target,s=o.get(e.edge.id)?.target;return"number"==typeof n&&Number.isFinite(n)&&"number"==typeof s&&Number.isFinite(s)&&n!==s?"top"===t.side?n-s:s-n:0}if("in"===t.kind){if(t.edge.source===e.edge.source&&t.edge.startTime===e.edge.startTime)return 0;const n=o.get(t.edge.id)?.source,s=o.get(e.edge.id)?.source;return"number"==typeof n&&Number.isFinite(n)&&"number"==typeof s&&Number.isFinite(s)&&n!==s?"top"===t.side?s-n:n-s:0}return 0})(t,e)||u(t.edge?.id??"",e.edge?.id??"")||u(t.side,e.side)||t.delta-e.delta)},f=r.length?function(t,e=1/0){let n=e;for(const e of t)e<n&&(n=e);return n}(r.map(t=>t.time)):null,d=Array.isArray(t.xExtent)&&Number.isFinite(t.xExtent[0])?t.xExtent[0]:null,g=null!=d?d-1:null!=f&&Number.isFinite(f)?f-1:null;c();let m=null,p=0;for(const t of r)t.time!==m&&(m=t.time,p=0),t.sequence=p++;const h=t=>({time:t.time,phase:0,sequence:t.sequence??0}),b=[];let M=0,y=0;for(const t of r)if("out"===t.kind){const e=Math.abs(t.delta);let n=e-("top"===t.side?M:y);if(n>0){const e="top"===t.side?"bot":"top",o="top"===e?M:y,s=Math.min(n,o);if(s>0){const o=h(t);b.push({...o,delta:-s,kind:"transfer-out",side:e}),b.push({...o,delta:+s,kind:"transfer-in",side:t.side}),"top"===e?M-=s:y-=s,"top"===t.side?M+=s:y+=s,n-=s}n>0&&null!==g&&(b.push({time:g,delta:+n,kind:"create",side:t.side}),"top"===t.side?M+=n:y+=n)}"top"===t.side?M-=e:y-=e}else if("in"===t.kind){const e=Math.abs(t.delta);"top"===t.side?M+=e:y+=e}r.push(...b),c();let x=0,w=0,v=0,k=0,T=0,S=0;const N=[],O=new Map,P=t=>{N.push({t:t,topMass:x,botMass:w,...Math.abs(v)>1e-12&&{boundaryOffset:v}})},F=()=>{k=Math.max(k,x+w),T=Math.max(T,x-v),S=Math.max(S,w+v)};for(const t of r){if("transfer-out"!==t.kind&&"transfer-in"!==t.kind&&P(t.time),("in"===t.kind||"out"===t.kind)&&t.edge){const e="top"===t.side?x:w,n=e+t.delta;O.set(t.edge.id,{side:t.side,time:t.time,sideMassBefore:e,sideMassAfter:n,kind:t.kind,value:Math.abs(t.delta),...Math.abs(v)>1e-12&&{boundaryOffset:v}})}"top"===t.side?x+=t.delta:w+=t.delta,"transfer-in"===t.kind?(v+="top"===t.side?t.delta:-t.delta,F(),P(t.time)):"transfer-out"!==t.kind&&(F(),"out"===t.kind&&x+w<=1e-12&&(v=0),P(t.time))}const A=[];let I=0;for(;I<N.length;){let t=I;for(;t+1<N.length&&N[t+1].t===N[I].t;)t++;A.push(N[I]);for(let e=I+1;e<=t;e++){const t=A[A.length-1];N[e].topMass===t.topMass&&N[e].botMass===t.botMass&&(N[e].boundaryOffset??0)===(t.boundaryOffset??0)||A.push(N[e])}I=t+1}const E=Array.isArray(t.xExtent)&&Number.isFinite(t.xExtent[1])?t.xExtent[1]:null;let $=null;for(const t of a)null!=t.systemInTime&&Number.isFinite(t.systemInTime)&&t.systemInTime<t.startTime&&(null===$||t.systemInTime<$)&&($=t.systemInTime);let L=null;for(const t of i)null!=t.systemOutTime&&Number.isFinite(t.systemOutTime)&&t.systemOutTime>t.endTime&&(null===L||t.systemOutTime>L)&&(L=t.systemOutTime);if(A.length>0){const t=A[A.length-1],e=Math.max(null!=E?E:-1/0,null!=L?L:-1/0);Number.isFinite(e)&&e>t.t&&t.topMass+t.botMass>0&&A.push({t:e,topMass:t.topMass,botMass:t.botMass,...null!=t.boundaryOffset&&{boundaryOffset:t.boundaryOffset}});const n=A[0],o=A.find(t=>t.topMass+t.botMass>0);let s,i=1/0;null!=d&&Number.isFinite(d)&&d<n.t&&n.topMass+n.botMass>0&&(i=d,s=n),o&&null!=$&&Number.isFinite($)&&$<o.t&&$<i&&(i=$,s=o),s&&Number.isFinite(i)&&A.unshift({t:i,topMass:s.topMass,botMass:s.botMass,...null!=s.boundaryOffset&&{boundaryOffset:s.boundaryOffset}})}let B=A;if("max"===s&&null!=d&&null!=E&&E>d){let t,e=0;for(const n of A){const o=n.topMass+n.botMass;o>e&&(e=o,t=n)}if(t){const e={topMass:t.topMass,botMass:t.botMass,...null!=t.boundaryOffset&&{boundaryOffset:t.boundaryOffset}};B=[...A.filter(t=>t.t<d),{t:d,...e},{t:E,...e},...A.filter(t=>t.t>E)]}}return{samples:B,peak:k,topPeak:T,botPeak:S,localAttachments:O}}function F(t){const e={};return t.forEach((t,n)=>{for(const o of t.occupants)e[o.id]=n}),e}function A(t,e,n){t.splice(0,t.length,...n);const o=F(n);for(const t of Object.keys(e))delete e[t];Object.assign(e,o)}function I(t){const e=new Map,n=[];t.forEach((t,o)=>{if(!t.group)return void n.push({anchor:o,stableId:f(t),slots:[t]});const s=e.get(t.group)??{indexes:[],slots:[]};s.indexes.push(o),s.slots.push(t),e.set(t.group,s)});for(const[t,o]of e)n.push({anchor:o.indexes.reduce((t,e)=>t+e,0)/o.indexes.length,stableId:`${t}\0${o.slots.map(f).join("\0")}`,slots:o.slots});return n.sort((t,e)=>t.anchor-e.anchor||u(t.stableId,e.stableId))}function E(t){return t.some(t=>t.group)?I(t).flatMap(t=>t.slots):[...t]}function $(t){return t.flatMap(t=>t.slots)}function L(t,e,n){const o=new Map;return t.forEach((t,e)=>{for(const n of t.slots)o.set(n,e)}),t.map((t,s)=>{if(t.slots.length<=1)return t;const i=new Map;for(const e of t.slots)i.set(e,0);for(const t of e){const e=o.get(t.source),n=o.get(t.target);if(null==e||null==n)continue;const a=Number.isFinite(t.weight)&&t.weight>0?t.weight:1;if(e===s&&n!==s){const e=n>s?1:-1;i.set(t.source,(i.get(t.source)??0)+a*e)}else if(n===s&&e!==s){const n=e>s?1:-1;i.set(t.target,(i.get(t.target)??0)+a*n)}}const a=[...t.slots].sort((t,e)=>(i.get(t)??0)-(i.get(e)??0)||n(t,e));return{...t,slots:a}})}function B(t,e){t.some(t=>t.group)&&A(t,e,E(t))}function z(t,e){return t.source!==e.source&&t.target!==e.target&&t.source!==e.target&&t.target!==e.source&&Math.max(t.startTime,e.startTime)<Math.min(t.endTime,e.endTime)}function C(t,e){return function(t,e,n=()=>!0){let o=0;for(let s=0;s<t.length;s++){const[i,a]=e(t[s]);for(let r=s+1;r<t.length;r++){if(!n(t[s],t[r]))continue;const[l,c]=e(t[r]);(i-l)*(a-c)<0&&o++}}return o}(e,e=>[t[e.source],t[e.target]],z)}function X(t,e){let n=0;for(const o of e){const e=t[o.source],s=t[o.target];null!=e&&null!=s&&(n+=Math.abs(e-s)*(o.value>0?o.value:1))}return n}function H(t,e,n){const[o,s]=n.get(t.first),[i,a]=n.get(t.second);return(e.get(o)-e.get(i))*(e.get(s)-e.get(a))<0?1:0}var D=t=>{let e=1;for(let n=2;n<=t;n++)e*=n;return e},j=828*D(8),Y=3e3;function q(t,e,n,o,s,i,a){const d=[...s],m=new Map(s.map(t=>[t,f(t)])),p=new Map;for(const t of s)for(const e of t.occupants)p.set(e.id,t);const M=new Map,y=[];for(const t of e){const e=p.get(t.source),n=p.get(t.target);e&&n&&(M.set(t,[e,n]),e!==n&&y.push({source:e,target:n,weight:t.value}))}const x=[];for(let t=0;t<e.length;t++)if(M.has(e[t]))for(let n=t+1;n<e.length;n++){if(!M.has(e[n])||!z(e[t],e[n]))continue;const o=new Set([...M.get(e[t]),...M.get(e[n])]);x.push({index:x.length,first:e[t],second:e[n],involvedSlots:o})}const w=new Map;for(const t of s)w.set(t,[]);for(const t of x)for(const e of t.involvedSlots)w.get(e)?.push(t);const v=new Uint32Array(x.length);let T=0;const S=e.reduce((t,e)=>t+(e.value>0?e.value:1),0),N=a.plotH/Math.max(1,s.length),O=s.reduce((t,e)=>t+e.peak.topPeak+e.peak.botPeak,0),P=Math.max(1,S)*(Math.max(1,a.plotH)+N*Math.max(O,s.length)+1e-6*Math.max(1,s.length-1))+1,B=4*N,C={fullCrossing:0,localCrossing:0},q=new Map,V=(t,e)=>{let o=q.get(t);o||(o=new Map,q.set(t,o));const s=o.get(e);if(null!=s)return s;const i=function(t,e,n){return r(g([t,e],n)).adjacentClearance[0]??0}(t,e,n);return o.set(e,i),i},U=new Map(s.map((t,e)=>[t,e])),W=e.flatMap(t=>{const e=M.get(t);return e?[{source:U.get(e[0]),target:U.get(e[1]),weight:t.value>0?t.value:1}]:[]}),R=new Map;for(const t of e){const e=M.get(t);e&&R.set(t,{source:U.get(e[0]),target:U.get(e[1])})}const _=new Map,G=new Map;for(const t of e)_.has(t.source)||_.set(t.source,new Set),G.has(t.target)||G.set(t.target,new Set),_.get(t.source).add(t.target),G.get(t.target).add(t.source);const Z=e.flatMap(t=>{if(!(t=>{const e=new Set([..._.get(t.source)??[],...G.get(t.source)??[]]),n=new Set([..._.get(t.target)??[],...G.get(t.target)??[]]);return 1===_.get(t.source)?.size&&_.get(t.source).has(t.target)||1===e.size&&e.has(t.target)||1===n.size&&n.has(t.source)})(t))return[];const e=R.get(t);return e&&e.source!==e.target?[{source:e.source,target:e.target,weight:t.value>0?t.value:1}]:[]}),Q=t=>{let e=0;for(const n of Z)e+=Math.max(0,Math.abs(t[n.source]-t[n.target])-1)*n.weight;return e*B},J=t=>{const e=new Int16Array(s.length);for(let n=0;n<t.length;n++)e[U.get(t[n])]=n;return Q(e)},K=x.map(t=>{const e=R.get(t.first),n=R.get(t.second);return[e.source,e.target,n.source,n.target]}),tt=new Int16Array(s.length),et=new Float64Array(s.length),nt=new Float64Array(s.length+1),ot=t=>{for(let e=0;e<t.length;e++)tt[U.get(t[e])]=e;let e=0;for(const[t,n,o,s]of K)(tt[t]-tt[o])*(tt[n]-tt[s])<0&&e++;if(t.length>0){const e=U.get(t[0]);et[e]=a.padding+t[0].peak.topPeak*a.valueScale;for(let e=1;e<t.length;e++){const n=U.get(t[e-1]),o=U.get(t[e]);et[o]=et[n]+V(t[e-1],t[e])*a.valueScale+a.padding}const n=U.get(t[t.length-1]),o=et[n]+t[t.length-1].peak.botPeak*a.valueScale+a.padding;if(o>a.plotH&&o>0){const t=a.plotH/o;for(let e=0;e<et.length;e++)et[e]*=t}}nt[0]=0;for(let e=0;e<t.length;e++)nt[e+1]=nt[e]+t[e].peak.topPeak+t[e].peak.botPeak;let n=0,o=0,s=0;for(const t of W){const e=tt[t.source],i=tt[t.target];if(n+=Math.abs(e-i)*t.weight,o+=Math.abs(et[t.source]-et[t.target])*t.weight,Math.abs(e-i)>=2){const n=Math.min(e,i)+1,o=Math.max(e,i);s+=(nt[o]-nt[n])*t.weight}}return e*P+o+s*N+Q(tt)+1e-6*n},st=(t,n)=>{const o=new Array(t.length+1).fill(0);for(let e=0;e<t.length;e++)o[e+1]=o[e]+t[e].peak.topPeak+t[e].peak.botPeak;let s=0;for(const t of e){const e=n[t.source],i=n[t.target];if(null==e||null==i||Math.abs(e-i)<2)continue;const a=Math.min(e,i)+1;s+=(o[Math.max(e,i)]-o[a])*(t.value>0?t.value:1)}return s},it=o=>{const s=F(o),i=o.slice(0,-1).map((t,e)=>V(t,o[e+1])),r=h(t,e,n,o,s,{plotH:a.plotH,padding:a.padding,valueScale:a.valueScale,lanePlacement:a.lanePlacement??"stack",groupPadding:a.groupPadding,adjacentClearance:i});return{map:s,geometry:r,weightedLength:X(s,e),pixelLength:b(r.centerlines,e),transitOcclusion:st(o,s)}},at=(t,e,n)=>({crossings:t,weightedLength:e.weightedLength,pixelLength:e.pixelLength,transitOcclusion:e.transitOcclusion,cost:t*P+e.pixelLength+e.transitOcclusion*N+J(n)+1e-6*e.weightedLength}),rt=(t,e)=>{let n=e;if(null==n){const e=new Map(t.map((t,e)=>[t,e]));n=x.reduce((t,n)=>t+H(n,e,M),0),C.fullCrossing++}return at(n,it(t),t)},lt=(t,s,i="quality")=>{let r=s;if(null==r){const e=new Map(t.map((t,e)=>[t,e]));r=x.reduce((t,n)=>t+H(n,e,M),0),C.fullCrossing++}const l=it(t);return at(r,{...l,transitOcclusion:k(e,n,t,l.map,l.geometry.centerlines,o,{valueScale:a.valueScale,ribbonLane:a.ribbonLane,domain:a.domain,mode:i})},t)};let ct=[...d];const ut=(t,e)=>u(m.get(t),m.get(e)),ft=function(t){const e=new Set;for(const n of t)if(n.group){if(e.has(n.group))return!0;e.add(n.group)}return!1}(ct),dt=t=>{const e=(t=>{const e=l(t,y,t=>rt(t).cost,{passes:6,compare:ut,maxEvaluations:Y});let n=rt(e),o=Y;for(let t=0;t<6&&o>0;t++){let s=!1;const i=Array.from({length:e.length-1},(t,e)=>e);t%2==1&&i.reverse();for(const t of i){if(o--<=0)break;const i=e[t],a=e[t+1],r=new Map(e.map((t,e)=>[t,e]));let l=0;const c=[];T++;for(const t of[...w.get(i)??[],...w.get(a)??[]])v[t.index]!==T&&(v[t.index]=T,c.push(t),l+=H(t,r,M));[e[t],e[t+1]]=[a,i];const u=new Map(r);u.set(i,t+1),u.set(a,t);let f=0;for(const t of c)f+=H(t,u,M);C.localCrossing+=c.length;const d=rt(e,n.crossings-l+f);d.cost<n.cost?(n=d,s=!0):[e[t],e[t+1]]=[i,a]}if(!s)break}return e})(t);if((t.length<=8?D(t.length)*(t.length+W.length+K.length):1/0)>j)return e;const n=c(t,ot,{maxItems:8,maxEvaluations:5e4}),o=lt(n),s=lt(e);return o.crossings!==s.crossings&&o.crossings<s.crossings?n:e},gt=t=>{let e=I(t);if(e.length<=1)return $(e);const n=t=>rt($(t)).cost;e=I(dt(t)),e=L(e,y,ut);const o=function(t,e){const n=new Map;for(const e of t)for(const t of e.slots)n.set(t,e);const o=new Map;for(const t of e){const e=n.get(t.source),s=n.get(t.target);if(!e||!s||e===s)continue;const i=Number.isFinite(t.weight)&&t.weight>0?t.weight:1,a=e.stableId<s.stableId?`${e.stableId}\0${s.stableId}`:`${s.stableId}\0${e.stableId}`,r=o.get(a);r?r.weight=(r.weight??0)+i:o.set(a,{source:e,target:s,weight:i})}return[...o.values()]}(e,y);e=l(e,o,n,{passes:6,compare:(t,e)=>u(t.stableId,e.stableId),maxEvaluations:Y}),e=function(t,e,n={}){const o=[...t];if(o.length<=1)return o;let s=e(o),i=1;const a=Math.max(0,n.passes??6),r=Math.max(1,n.maxEvaluations??1/0);for(let t=0;t<a&&i<r;t++){let t=!1;for(let n=0;n<o.length-1&&i<r;n++){[o[n],o[n+1]]=[o[n+1],o[n]];const a=e(o);i++,a<s?(s=a,t=!0):[o[n],o[n+1]]=[o[n+1],o[n]]}if(!t)break}return o}(e,n,{passes:8,maxEvaluations:Y});if((e.length<=8?D(e.length)*(e.length+W.length+K.length):1/0)<=j){const t=c(e,t=>ot($(t)),{maxItems:8,maxEvaluations:5e4}),n=$(t),o=$(e),s=lt(n),i=lt(o);s.crossings!==i.crossings?e=s.crossings<i.crossings?t:e:s.cost<i.cost&&(e=t)}return e=L(e,y,ut),$(e)},mt="geometry-refine"===a.mode;if(mt||"crossing-min"!==a.laneOrder&&"crossing-min+inside-out"!==a.laneOrder){if(!mt&&"inside-out"===a.laneOrder)if(ft){const t=I(ct),e=t=>t.slots.reduce((t,e)=>t+e.peak.topPeak+e.peak.botPeak,0),n=[...t].sort((t,n)=>e(n)-e(t)||u(t.stableId,n.stableId)),o=new Array(n.length);let s=Math.floor((n.length-1)/2)-1,i=Math.floor((n.length-1)/2)+1;n.length>0&&(o[Math.floor((n.length-1)/2)]=n[0]);for(let t=1;t<n.length;t++)t%2==1&&i<n.length?o[i++]=n[t]:s>=0?o[s--]=n[t]:o[i++]=n[t];ct=$(o)}else{const t=[...ct].sort((t,e)=>{const n=t.peak.topPeak+t.peak.botPeak;return e.peak.topPeak+e.peak.botPeak-n||ut(t,e)}),e=new Array(t.length);let n=Math.floor((t.length-1)/2)-1,o=Math.floor((t.length-1)/2)+1;t.length>0&&(e[Math.floor((t.length-1)/2)]=t[0]);for(let s=1;s<t.length;s++)s%2==1&&o<t.length?e[o++]=t[s]:n>=0?e[n--]=t[s]:e[o++]=t[s];ct=e}}else ct=ft?gt(ct):dt(ct);if(!mt&&"crossing-min+inside-out"===a.laneOrder&&ct.length>1)if(ft){const t=I(ct);let e=rt($(t)),n=$(t),o=e;const s=Math.floor((t.length-1)/2),i=t=>t.slots.reduce((t,e)=>t+e.peak.topPeak+e.peak.botPeak,0),a=[...t].sort((t,e)=>i(e)-i(t)||u(t.stableId,e.stableId));for(const i of a){const a=t.indexOf(i);if(a===s)continue;t.splice(a,1),t.splice(s,0,i);const r=$(t),l=rt(r);l.cost<=e.cost?(e=l,l.cost<o.cost&&(n=r,o=l)):(t.splice(s,1),t.splice(a,0,i))}ct=n}else{let t=rt(ct),e=[...ct],n=t;const o=Math.floor((ct.length-1)/2),s=[...ct].sort((t,e)=>e.peak.topPeak+e.peak.botPeak-(t.peak.topPeak+t.peak.botPeak)||ut(t,e));for(const i of s){const s=ct.indexOf(i);if(s===o)continue;ct.splice(s,1),ct.splice(o,0,i);const a=rt(ct);a.cost<=t.cost?(t=a,a.cost<n.cost&&(e=[...ct],n=a)):(ct.splice(o,1),ct.splice(s,0,i))}ct=e}if((mt||"crossing-min"===a.laneOrder||"crossing-min+inside-out"===a.laneOrder)&&ct.length>1)if(ft){let t=I(ct),e=lt($(t),void 0,"score");for(let n=0;n<6&&t.length>1;n++){let n=!1;for(let o=0;o<t.length-1;o++){[t[o],t[o+1]]=[t[o+1],t[o]];const s=$(t),i=lt(s,void 0,"score");i.cost<e.cost?(ct=s,e=i,n=!0):[t[o],t[o+1]]=[t[o+1],t[o]]}if(!n)break}t=L(I(ct),y,ut),ct=$(t)}else{let t=lt(ct,void 0,"score");for(let e=0;e<ct.length-1;e++){const n=ct[e],o=ct[e+1],s=new Map(ct.map((t,e)=>[t,e]));let i=0;const a=[];T++;for(const t of[...w.get(n)??[],...w.get(o)??[]])v[t.index]!==T&&(v[t.index]=T,a.push(t),i+=H(t,s,M));[ct[e],ct[e+1]]=[o,n];const r=new Map(s);r.set(n,e+1),r.set(o,e);let l=0;for(const t of a)l+=H(t,r,M);C.localCrossing+=a.length;const c=lt(ct,t.crossings-i+l,"score");c.cost<t.cost?t=c:[ct[e],ct[e+1]]=[n,o]}}const pt=E(d);ct=E(ct);let ht=lt(ct);const bt=lt(pt);if(mt){const t=J(pt),e=J(ct);(ht.crossings>bt.crossings||ht.crossings===bt.crossings&&e>t+1e-9||ht.cost>bt.cost)&&(ct=pt,ht=bt)}else ht.cost>bt.cost&&(ct=pt,ht=bt);return A(s,i,ct),{before:bt,after:ht,initialOrder:d.map(t=>m.get(t)),evaluations:C}}function V(t,e,n){const o=t.map(t=>{const o=t.occupants.map(t=>({id:t.id,end:n[t.id]?.end??t.end}));let s=0,i=0;for(const t of o){const n=e[t.id];s=Math.max(s,n?.topPeak||0),i=Math.max(i,n?.botPeak||0)}return{occupants:o,peak:{topPeak:s,botPeak:i},...null!=t.group?{group:t.group}:{}}}),s={};return o.forEach((t,e)=>{for(const n of t.occupants)s[n.id]=e}),{slots:o,slotByNode:s}}var U=new Map;var W=1e-9,R=1e5;function _(t,e){let n=1/0,o=-1/0;for(const e of t?.samples??[])e.topMass+e.botMass<=W||(n=Math.min(n,e.t),o=Math.max(o,e.t));return Number.isFinite(n)&&Number.isFinite(o)?(null!=e.start&&(n=Math.max(n,e.start)),null!=e.end&&(o=Math.min(o,e.end)),o>=n?{start:n,end:o}:{start:null,end:null}):{start:null,end:null}}function G(t,e){return null!=t.start&&null!=t.end&&null!=e.start&&null!=e.end&&!(t.end<=e.start||e.end<=t.start)}function Z(t,e){return u(t,e)<=0?`${t}\0${e}`:`${e}\0${t}`}function Q(t){const e=new Map,n=new Map;for(const o of t)n.has(o.source)||n.set(o.source,new Set),e.has(o.target)||e.set(o.target,new Set),n.get(o.source).add(o.target),e.get(o.target).add(o.source);return{incoming:new Map([...e].map(([t,e])=>[t,e.size])),outgoing:new Map([...n].map(([t,e])=>[t,e.size]))}}function J(t){const e=new Map,n=new Map,o=(t,e,n,o)=>{let s=t.get(e);s||(s=new Map,t.set(e,s)),s.set(n,(s.get(n)??0)+o)};for(const s of t){const t=s.value>0&&Number.isFinite(s.value)?s.value:1;o(e,s.source,s.target,t),o(n,s.target,s.source,t)}const s=new Map,i=t=>{if(s.has(t))return;const o=e.get(t),i=n.get(t);if(o&&1===o.size&&(!i||0===i.size)){const[e,n]=[...o][0];return void s.set(t,{partner:e,weight:n})}const a=new Map;for(const[t,e]of o??[])a.set(t,(a.get(t)??0)+e);for(const[t,e]of i??[])a.set(t,(a.get(t)??0)+e);if(1===a.size){const[e,n]=[...a][0];s.set(t,{partner:e,weight:n})}};for(const e of t)i(e.source),i(e.target);return s}function K(t,e,n){const o=n.get(t),s=n.get(e);return!o||!s||(o.partner===s.partner||(o.partner===e||s.partner===t))}function tt(t,e,n){return!!n.has(t)&&e.some(e=>!K(t,e,n))}function et(t,e){return(t.value>0&&Number.isFinite(t.value)?t.value:1)*(1+(1===e.outgoing.get(t.source)?1:0)+(1===e.incoming.get(t.target)?1:0))}function nt(t,e,n,o){if(t.length<=12||o.slotCount<=1)return o.assignment;const s=new Map(t.map((t,e)=>[t,e])),i=Array.from({length:t.length},()=>new Map),a=Q(n);for(const t of n){const e=s.get(t.source),n=s.get(t.target);if(null==e||null==n||e===n)continue;const o=et(t,a);i[e].set(n,(i[e].get(n)??0)+o),i[n].set(e,(i[n].get(e)??0)+o)}const r=J(n),l=t.map(t=>r.get(t)?.weight??0),c=Array.from({length:t.length},()=>new Map);let u=0;for(let n=0;n<t.length-1&&u<5e4;n++)if(r.has(t[n]))for(let o=n+1;o<t.length;o++){if(!r.has(t[o]))continue;if(e.conflicts(t[n],t[o]))continue;u++;const s=Math.min(l[n],l[o])||Math.max(l[n],l[o]),i=K(t[n],t[o],r)?s:-s;if(!(Math.abs(i)<=W)&&(c[n].set(o,i),c[o].set(n,i),u>=5e4))break}const f=[...o.assignment],d=Array.from({length:o.slotCount},()=>[]);f.forEach((t,e)=>d[t].push(e));const g=(t,e,n)=>{const o=f[e],s=f[n];let i=0;const a=new Set;for(const r of[e,n])for(const[l,c]of t[r]){const t=r<l?`${r}:${l}`:`${l}:${r}`;if(a.has(t))continue;a.add(t);const u=f[r]===f[l],d=(r===e?s:o)===(l===e?s:l===n?o:f[l]);u!==d&&(i+=d?c:-c)}return i},m=(t,e,n)=>{let o=0;for(const[s,i]of t[e]){const t=f[e]===f[s],a=n===f[s];t!==a&&(o+=a?i:-i)}return o},p=(t,e)=>t>W||Math.abs(t)<=W&&e>W,h=(t,e,n,o)=>t>n+W||Math.abs(t-n)<=W&&e>o+W;let b=0;for(let n=0;n<32&&b<R;n++){let n=null,o=-1,s=-1,a=-1,r=-1/0,l=-1/0;for(let u=0;u<t.length;u++){for(let g=0;g<d.length&&!(b++>=R);g++){if(g===f[u])continue;if(!d[g].every(n=>!e.conflicts(t[u],t[n])))continue;const b=m(i,u,g),M=m(c,u,g);p(b,M)&&h(b,M,r,l)&&(n="move",o=u,s=-1,a=g,r=b,l=M)}if(b>=R)break}for(let u=0;u<t.length-1;u++){for(let m=u+1;m<t.length&&!(b++>=R);m++){const b=f[u],M=f[m];if(b===M)continue;if(!d[M].every(n=>n===m||!e.conflicts(t[u],t[n])))continue;if(!d[b].every(n=>n===u||!e.conflicts(t[m],t[n])))continue;const y=g(i,u,m),x=g(c,u,m);p(y,x)&&h(y,x,r,l)&&(n="swap",o=u,s=m,a=-1,r=y,l=x)}if(b>=R)break}if(null==n||-1===o)break;if("move"===n){const t=f[o];d[t].splice(d[t].indexOf(o),1),d[a].push(o),f[o]=a;continue}const u=f[o],M=f[s];d[u].splice(d[u].indexOf(o),1,s),d[M].splice(d[M].indexOf(s),1,o),f[o]=M,f[s]=u}return f}function ot(t,e,n,o){if(0===t.length||t.length>12||o.slotCount<=1)return o.assignment;const s=new Map(t.map((t,e)=>[t,e])),i=Array.from({length:t.length},()=>new Float64Array(t.length)),a=Array.from({length:t.length},()=>new Map),r=Array.from({length:t.length},()=>new Map),l=Q(n);for(const t of n){const e=s.get(t.source),n=s.get(t.target);if(null==e||null==n||e===n)continue;const o=et(t,l);i[e][n]+=o,i[n][e]+=o,r[e].set(n,(r[e].get(n)??0)+o),a[n].set(e,(a[n].get(e)??0)+o)}const c=J(n),u=t.map(t=>c.get(t)?.weight??0),f=Array.from({length:t.length},()=>new Float64Array(t.length));for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){for(const[t,o]of a[e])f[e][n]+=Math.min(o,a[n].get(t)??0);for(const[t,o]of r[e])f[e][n]+=Math.min(o,r[n].get(t)??0);if(c.has(t[e])&&c.has(t[n])){const o=Math.min(u[e],u[n])||Math.max(u[e],u[n]);f[e][n]+=K(t[e],t[n],c)?o:-o}f[n][e]=f[e][n]}let d=[...o.assignment],g=(e=>{let n=0,o=0;for(let s=0;s<t.length;s++)for(let a=s+1;a<t.length;a++)e[s]===e[a]&&(n+=i[s][a],o+=f[s][a]);return{flow:n,affinity:o}})(d),m=0;const p=new Array(t.length).fill(-1),h=Array.from({length:o.slotCount},()=>[]),b=(n,s,a,r)=>{if(m>=75e3)return;if(n===t.length)return m++,void((a>g.flow||a===g.flow&&r>g.affinity||a===g.flow&&r===g.affinity&&function(t,e){for(let n=0;n<Math.min(t.length,e.length);n++)if(t[n]!==e[n])return t[n]<e[n];return t.length<e.length}(p,d))&&(d=[...p],g={flow:a,affinity:r}));const l=Math.min(s+1,o.slotCount-1);for(let o=0;o<=l;o++){if(h[o].some(o=>e.conflicts(t[n],t[o])))continue;let l=0,c=0;for(const t of h[o])l+=i[n][t],c+=f[n][t];if(p[n]=o,h[o].push(n),b(n+1,Math.max(s,o),a+l,r+c),h[o].pop(),p[n]=-1,m>=75e3)return}};return p[0]=0,h[0].push(0),b(1,0,0,0),d}function st(t,e,n,o){const s=function(t,e,n,o){return`${t.map(t=>{const e=n[t.id],s=o[t.id];return[t.id,t.group??"",t.xExtent?.[0]??"",t.xExtent?.[1]??"",e?.topPeak??0,e?.botPeak??0,s?.start??"",s?.end??""].join(":")}).join("|")}#${e.map(t=>[t.id,t.source,t.target,t.value,t.startTime,t.endTime].join(":")).join("|")}`}(t,e,n,o),i=(a=s,U.get(a));var a;if(i)return V(i.slots,n,o);const r={};for(const e of t)r[e.id]=_(n[e.id],o[e.id]);const l=function(t,e){return t.filter(t=>null!=e[t.id].start).sort((t,n)=>e[t.id].start-e[n.id].start||e[t.id].end-e[n.id].end||u(t.id,n.id)).map(t=>t.id)}(t,r),c=new Map(t.map(t=>[t.id,t])),f=new Map(t.map(t=>[t.id,t.group||void 0])),d=function(t,e,n,o,s){const i=new Set,a=new Map(t.map(t=>[t,new Set])),r=new Map(t.map(t=>[t,new Set]));for(const t of o)i.add(Z(t.source,t.target)),a.get(t.target)?.add(t.source),r.get(t.source)?.add(t.target);const l=new Map,c=new Set,u=(t,e)=>{for(let n=0;n<t.length;n++)for(let o=n+1;o<t.length;o++){const s=Z(t[n],t[o]);e instanceof Map?e.set(s,[t[n],t[o]]):e.add(s)}};for(const t of r.values())u([...t],l);for(const t of a.values())u([...t],c);const f=new Set;for(const[t,[o,s]]of l)c.has(t)&&(G(e[o],e[s])||G(n[o],n[s])&&(f.add(o),f.add(s)));return{conflicts:(t,n)=>{const o=s.get(t),a=s.get(n);return null!=o&&null!=a&&o!==a||null!=o!=(null!=a)&&!i.has(Z(t,n))||!!G(e[t],e[n])||!(!f.has(t)&&!f.has(n))&&!i.has(Z(t,n))}}}(l,r,o,e,f),g=function(t,e,n=new Map){const o=[],s=[];for(const i of t){let t=o.findIndex(t=>t.every(t=>!e.conflicts(i,t))&&!tt(i,t,n));-1!==t||n.has(i)||(t=o.findIndex(t=>t.every(t=>!e.conflicts(i,t)))),-1===t&&(t=o.length,o.push([])),o[t].push(i),s.push(t)}return{assignment:s,slotCount:o.length}}(l,d,J(e)),m=ot(l,d,e,{...g,assignment:nt(l,d,e,g)}),p=new Map,h=m.map(t=>(p.has(t)||p.set(t,p.size),p.get(t))),b=Array.from({length:p.size||(t.length>0?1:0)},()=>({occupants:[],peak:{topPeak:0,botPeak:0}})),M={};l.forEach((t,e)=>{const n=h[e],o=b[n];o.occupants.push({id:t,end:r[t].end??-1/0});const s=c.get(t)?.group;s&&(o.group=s),M[t]=n});for(const e of[...t].sort((t,e)=>u(t.id,e.id)))null==M[e.id]&&(b[0].occupants.push({id:e.id,end:-1/0}),M[e.id]=0);for(const t of b){t.occupants.sort((t,e)=>(r[t.id].start??1/0)-(r[e.id].start??1/0)||u(t.id,e.id));for(const e of t.occupants){const o=n[e.id];t.peak.topPeak=Math.max(t.peak.topPeak,o?.topPeak||0),t.peak.botPeak=Math.max(t.peak.botPeak,o?.botPeak||0)}}const y={slots:b,slotByNode:M};return function(t,e){for(U.has(t)&&U.delete(t),U.set(t,{slots:e.slots.map(t=>({occupants:t.occupants.map(t=>({...t})),peak:{...t.peak},...null!=t.group?{group:t.group}:{}})),slotByNode:{...e.slotByNode}});U.size>12;){const t=U.keys().next().value;if(null==t)break;U.delete(t)}}(s,y),y}function it(t){return t.topMass+t.botMass}function at(t,e){const n=t.samples.filter(t=>t.t===e);if(n.length>0)return n.reduce((t,e)=>it(e)>=it(t)?e:t,n[0]);let o=null;for(const n of t.samples){if(n.t>e)break;o=n}return o}function rt(t,e,n,o,s,i,a=0){const r=new Map;for(const n of t){if(!n.group||!e[n.id])continue;const t=r.get(n.group)??[];t.push(n),r.set(n.group,t)}if(0===r.size||!(i>0))return e;const l=(c=e,Object.fromEntries(Object.entries(c).map(([t,e])=>[t,{...e,samples:e.samples.map(t=>({...t})),localAttachments:new Map([...e.localAttachments].map(([t,e])=>[t,{...e}]))}])));var c;for(const[t,c]of r){const r=n.map((t,e)=>({slot:t,index:e})).filter(({slot:e})=>e.group===t);if(0===r.length)continue;const u=r[0].slot,f=r.at(-1).slot,d=s[u.occupants[0]?.id],g=s[f.occupants[0]?.id];if(!Number.isFinite(d)||!Number.isFinite(g))continue;const m=(d-u.peak.topPeak*i+(g+f.peak.botPeak*i))/2,p=[...new Set(c.flatMap(t=>e[t.id].samples.map(t=>t.t)))].sort((t,e)=>t-e),h=new Map;for(const t of c)h.set(t.id,new Map);for(const t of p){const n=new Map;for(const s of c){const i=at(e[s.id],t);if(!i||it(i)<=1e-9)continue;const a=o[s.id];if(null==a)continue;const r=n.get(a)??[];r.push({node:s,sample:i}),n.set(a,r)}const r=[...n].sort((t,e)=>t[0]-e[0]).map(([t,e])=>({slot:t,active:e,mass:Math.max(...e.map(({sample:t})=>it(t)))}));if(0===r.length)continue;let l=m-(r.reduce((t,e)=>t+e.mass,0)*i+Math.max(0,a)*Math.max(0,r.length-1))/2;for(const e of r){for(const{node:n,sample:o}of e.active){const e=(l-s[n.id])/i+o.topMass-(o.boundaryOffset??0);h.get(n.id).set(t,e)}l+=e.mass*i+Math.max(0,a)}}for(const t of c){const n=e[t.id],o=l[t.id],s=h.get(t.id),i=[];for(const t of p){const e=s.get(t),o=n.samples.filter(e=>e.t===t);if(o.length>0){i.push(...o.map(t=>({...t,...null!=e?{boundaryOffset:(t.boundaryOffset??0)+e}:{}})));continue}const a=at(n,t);null==e||!a||it(a)<=1e-9||i.push({...a,t:t,boundaryOffset:(a.boundaryOffset??0)+e})}o.samples=i,o.localAttachments=new Map([...n.localAttachments].map(([t,e])=>{const n=s.get(e.time);return[t,{...e,...null!=n?{boundaryOffset:(e.boundaryOffset??0)+n}:{}}]}))}}return l}function lt(t,e,n,o,s){const{plotH:i,padding:a,valueScale:r,packing:l,laneOrder:c,lifetimeMode:d="half",lanePlacement:g="stack",groupPadding:m=0,ribbonLane:p="both",domain:b}=s,M={},y={};for(const e of t)M[e.id]=n[e.id].topPeak||0,y[e.id]=n[e.id].botPeak||0;const x="half"===d,w={};for(const e of t){const t=Array.isArray(e.xExtent)?e.xExtent[0]:null,n=Array.isArray(e.xExtent)?e.xExtent[1]:null;let s=null!=t&&Number.isFinite(t)?t:1/0,i=null!=n&&Number.isFinite(n)?n:-1/0;for(const t of o.outgoing[e.id]){t.startTime<s&&(s=t.startTime),null!=t.systemInTime&&Number.isFinite(t.systemInTime)&&t.systemInTime<s&&(s=t.systemInTime);const e=x?(t.startTime+t.endTime)/2:t.endTime;e>i&&(i=e)}for(const t of o.incoming[e.id]){const e=x?(t.startTime+t.endTime)/2:t.startTime;e<s&&(s=e),t.endTime>i&&(i=t.endTime),null!=t.systemOutTime&&Number.isFinite(t.systemOutTime)&&t.systemOutTime>i&&(i=t.systemOutTime)}w[e.id]={start:Number.isFinite(s)?s:null,end:Number.isFinite(i)?i:null}}let v={},k=[],T=[];if(s.frozenSlots){const t=V(s.frozenSlots,n,w);k=t.slots,v=t.slotByNode,T=k.map(f)}else if("reuse"===l){const o=st(t,e,n,w);k=o.slots,v=o.slotByNode}else t.forEach((t,e)=>{k.push({occupants:[{id:t.id,end:w[t.id]?.end??-1/0}],peak:{topPeak:M[t.id],botPeak:y[t.id]},...t.group?{group:t.group}:{}}),v[t.id]=e});B(k,v),0===T.length&&(T=k.map(f));let S=null;s.frozenSlots||(s.fixedSlotOrder?function(t,e,n){const o=new Map(n.map((t,e)=>[t,e]));A(t,e,[...t].sort((t,e)=>(o.get(f(t))??1/0)-(o.get(f(e))??1/0)||u(f(t),f(e))))}(k,v,s.fixedSlotOrder):s.runOrdering&&c&&"insertion"!==c&&(S=q(t,e,n,w,k,v,{plotH:i,padding:a,valueScale:r,groupPadding:m,laneOrder:c,ribbonLane:p,domain:b}))),B(k,v);const N=h(t,e,n,k,v,{plotH:i,padding:a,valueScale:r,stackValueScale:s.stackValueScale,lanePlacement:g,groupPadding:m}),O=0===k.length?0:k[0].peak.topPeak+N.adjacentClearance.reduce((t,e)=>t+e,0)+k[k.length-1].peak.botPeak,P=S?.before.crossings??null,F=S?.after.crossings??null,I=S?.before.weightedLength??null,E=S?.after.weightedLength??null;return{effectiveSlotsHeight:O,centerlines:N.centerlines,laneLifetime:w,slots:k,slotByNode:v,slotCenter:N.slotCenter,stackCenter:N.stackCenter,verticalUtilization:N.verticalUtilization,selectedSlotOrder:k.map(f),initialSlotOrder:T,ordering:S,crossingsBefore:P,crossingsAfter:F,lengthBefore:I,lengthAfter:E}}function ct(t,e,n){const{plotH:o,pairing:s="temporal",packing:i="reuse",laneOrder:a="crossing-min",lifetimeMode:r="half",maxValueScale:l,lanePlacement:c="stack",nodeSizing:g="temporal",groupPadding:m=0,ribbonLane:p="both",domain:b}=n,M=Number.isFinite(m)?Math.max(0,m):0,y=function(t,e){const n={},o={};for(const e of t)n[e.id]=[],o[e.id]=[];for(const t of e)o[t.source]&&o[t.source].push(t),n[t.target]&&n[t.target].push(t);return{incoming:n,outgoing:o}}(t,e),x=function(t,e,n,o="temporal"){const s="temporal"===o?(t,e)=>t.endTime-e.endTime||u(t.id,e.id):(t,e)=>e.value-t.value||u(t.id,e.id),i="temporal"===o?(t,e)=>t.startTime-e.startTime||u(t.id,e.id):(t,e)=>e.value-t.value||u(t.id,e.id),a=new Map;for(const t of e)a.set(t.id,{});const r=(t,e)=>{const n=new Map;for(const o of t){const t=o[e];n.has(t)||n.set(t,{partner:t,edges:[],total:0,earliestStart:1/0,latestEnd:-1/0});const s=n.get(t);s.edges.push(o),s.total+=o.value,s.earliestStart=Math.min(s.earliestStart,o.startTime),s.latestEnd=Math.max(s.latestEnd,o.endTime)}const a=[...n.values()];"temporal"===o?a.sort((t,n)=>"target"===e?t.earliestStart-n.earliestStart||u(t.partner,n.partner):t.latestEnd-n.latestEnd||u(t.partner,n.partner)):a.sort((t,e)=>e.total-t.total||u(t.partner,e.partner));for(const t of a)t.edges.sort("target"===e?i:s);return a};for(const e of t){const t=n.outgoing[e.id],o=n.incoming[e.id];if(0===o.length)r(t,"target").forEach((t,e)=>{const n=e%2==0?"top":"bot";for(const e of t.edges)a.get(e.id).sourceSide=n});else if(0===t.length)r(o,"source").forEach((t,e)=>{const n=e%2==0?"top":"bot";for(const e of t.edges)a.get(e.id).targetSide=n});else{const e=r(o,"source"),n=r(t,"target"),s=Math.max(e.length,n.length);for(let t=0;t<s;t++){const o=t%2==0?"top":"bot";if(e[t])for(const n of e[t].edges)a.get(n.id).targetSide=o;if(n[t])for(const e of n[t].edges)a.get(e.id).sourceSide=o}}}return a}(t,e,y,s);let w={};for(const e of t)w[e.id]=P(e,y,x,void 0,g);const v=lt(t,e,w,y,{plotH:o,padding:12,valueScale:1,packing:i,laneOrder:a,lifetimeMode:r,runOrdering:!0,lanePlacement:"stack",groupPadding:M,ribbonLane:p,domain:b}),k=v.slots.map(t=>({occupants:t.occupants.map(t=>({...t})),peak:{...t.peak},...null!=t.group?{group:t.group}:{}})),S=new Set;for(const t of e){const e=v.slotByNode[t.source],n=v.slotByNode[t.target];if(void 0===e||void 0===n)continue;const o=x.get(t.id);e!==n?n<e?(o.sourceSide="top",o.targetSide="bot"):(o.sourceSide="bot",o.targetSide="top"):(S.add(t.id),o.sourceSide="bot",o.targetSide="bot")}for(const e of t){const t=y.outgoing[e.id],n=y.incoming[e.id],o=new Set(t.map(t=>x.get(t.id).sourceSide)),s=new Set(n.map(t=>x.get(t.id).targetSide));if(1===o.size&&n.length>0){const t=[...o][0];for(const e of n)v.slotByNode[e.source]===v.slotByNode[e.target]&&(x.get(e.id).targetSide=t)}if(1===s.size&&t.length>0){const e=[...s][0];for(const n of t)v.slotByNode[n.source]===v.slotByNode[n.target]&&(x.get(n.id).sourceSide=e)}}!function(t,e,n){const o=new Map,s=[];for(const e of t)s.push({time:e.startTime,kind:"out",edge:e}),s.push({time:e.endTime,kind:"in",edge:e});s.sort((t,e)=>t.time-e.time||(t.kind===e.kind?0:"in"===t.kind?-1:1)||("out"===t.kind?e.edge.value-t.edge.value:0)||u(t.edge.id,e.edge.id));const i=t=>{let e=o.get(t);return e||(e={top:0,bot:0},o.set(t,e)),e},a=(t,e,n)=>{const o="top"===e?"bot":"top",s=Math.min(n,t[e]);t[e]-=s;const i=n-s;i>0&&(t[o]=Math.max(0,t[o]-i))};for(const t of s){const{edge:o}=t;if("in"===t.kind){const t=e.get(o.id)?.targetSide??"bot";i(o.target)[t]+=o.value;continue}const s=i(o.source),r=e.get(o.id);let l=r.sourceSide??"bot";if(n[o.source]===n[o.target]){const t=s.top>=o.value,e=s.bot>=o.value;t!==e?l=t?"top":"bot":t||e||s.top===s.bot||(l=s.top>s.bot?"top":"bot"),r.sourceSide=l,r.targetSide=l}a(s,l,o.value)}}(e,x,v.slotByNode),function(t,e,n,o){for(const s of t){const t=e.incoming[s.id],i=e.outgoing[s.id];if(0===t.length||0===i.length)continue;const a=()=>{const e={inTop:0,inBot:0,outTop:0,outBot:0};for(const o of t)"top"===n.get(o.id).targetSide?e.inTop+=o.value:e.inBot+=o.value;for(const t of i)"top"===n.get(t.id).sourceSide?e.outTop+=t.value:e.outBot+=t.value;return e},r=(t,e)=>{const s=a(),r="top"===t?s.outTop-s.inTop:s.outBot-s.inBot,l="top"===e?s.inTop-s.outTop:s.inBot-s.outBot;if(r<=0||l<=0)return!1;const c=Math.min(r,l),f=i.filter(e=>!o.has(e.id)&&n.get(e.id).sourceSide===t&&e.value<=c).sort((t,e)=>e.value-t.value||u(t.id,e.id));return 0!==f.length&&(n.get(f[0].id).sourceSide=e,!0)};let l=i.length+1;for(;l-- >0&&(r("top","bot")||r("bot","top")););}}(t,y,x,S),w={};for(const e of t)w[e.id]=P(e,y,x,void 0,g);const N=lt(t,e,w,y,{plotH:o,padding:12,valueScale:1,packing:i,laneOrder:a,lifetimeMode:r,frozenSlots:k,lanePlacement:"stack",groupPadding:M,ribbonLane:p,domain:b}),F=N.effectiveSlotsHeight??N.slots.reduce((t,e)=>t+e.peak.topPeak+e.peak.botPeak,0),A=N.slots.slice(0,-1).reduce((t,e,n)=>t+(null!=e.group&&e.group===N.slots[n+1].group?1:0),0),I=Math.max(1,N.slots.length+1-A),E=Math.min(12,Math.max(0,.35*o-A*M)/I),$=2*E+d(N.slots,E,M).reduce((t,e)=>t+e,0),L=F>0?Math.max(0,(o-$)/F):1,B=Number.isFinite(l)&&l>0?Math.min(L,l):L;let z=lt(t,e,w,y,{plotH:o,padding:E,valueScale:B,packing:i,laneOrder:a,lifetimeMode:r,frozenSlots:k,lanePlacement:c,groupPadding:M,ribbonLane:p,domain:b,stackValueScale:L});const H=Number.isFinite(l)&&l>0&&l+1e-12<L;if("insertion"!==a&&("hug"===c||H)&&z.slots.length>1&&(q(t,e,w,z.laneLifetime,z.slots,z.slotByNode,{plotH:o,padding:E,valueScale:B,groupPadding:M,laneOrder:a,ribbonLane:p,domain:b,lanePlacement:c,mode:"geometry-refine"}),z=lt(t,e,w,y,{plotH:o,padding:E,valueScale:B,packing:i,laneOrder:a,lifetimeMode:r,frozenSlots:z.slots,fixedSlotOrder:z.slots.map(f),lanePlacement:c,groupPadding:M,ribbonLane:p,domain:b,stackValueScale:L})),function(t,e){const n=(t,n)=>{for(const o of t){const t=new Map;for(const s of o){const o=`${("out"===n?e.get(s.id)?.sourceSide:e.get(s.id)?.targetSide)??""}\0${"out"===n?s.startTime:s.endTime}`,i="out"===n?`${s.target}\0${s.endTime}`:`${s.source}\0${s.startTime}`,a=t.get(o);if(null!=a&&a!==i)return!0;t.set(o,i)}}return!1};return n(Object.values(t.outgoing),"out")||n(Object.values(t.incoming),"in")}(y,x)){const n=function(t,e,n,o){const s=new Map;for(const i of t){const t=e[i.source]?.localAttachments.get(i.id),a=e[i.target]?.localAttachments.get(i.id),r=n[i.source],l=n[i.target];if(!(t&&a&&Number.isFinite(r)&&Number.isFinite(l)))continue;const c=O(t,r,o),u=O(a,l,o);s.set(i.id,{source:(c[0]+c[1])/2,target:(u[0]+u[1])/2})}return s}(e,w,z.centerlines,B);w={};for(const e of t)w[e.id]=P(e,y,x,n,g);z=lt(t,e,w,y,{plotH:o,padding:E,valueScale:B,packing:i,laneOrder:a,lifetimeMode:r,frozenSlots:z.slots,fixedSlotOrder:z.slots.map(f),lanePlacement:c,groupPadding:M,ribbonLane:p,domain:b,stackValueScale:L})}const D=new Map(v.initialSlotOrder.map((t,e)=>[t,e])),j=[...z.slots].sort((t,e)=>(D.get(f(t))??1/0)-(D.get(f(e))??1/0)||u(f(t),f(e))),Y={};j.forEach((t,e)=>{for(const n of t.occupants)Y[n.id]=e});const V=h(t,e,w,j,Y,{plotH:o,padding:E,valueScale:B,stackValueScale:L,lanePlacement:"stack",groupPadding:M}),U=rt(t,w,j,Y,V.centerlines,B,M),W=T(C(Y,e),X(Y,e),e,U,j,Y,V.centerlines,z.laneLifetime,B,V.verticalUtilization,p,b);w=rt(t,w,z.slots,z.slotByNode,z.centerlines,B,M);const R=T(C(z.slotByNode,e),X(z.slotByNode,e),e,w,z.slots,z.slotByNode,z.centerlines,z.laneLifetime,B,z.verticalUtilization,p,b);return{nodeData:w,sides:x,valueScale:B,padding:E,compressedPadding:E<12,centerlines:z.centerlines,laneLifetime:z.laneLifetime,slots:z.slots,slotByNode:z.slotByNode,crossingsBefore:"insertion"===a?null:W.crossings,crossingsAfter:"insertion"===a?null:R.crossings,lengthBefore:"insertion"===a?null:W.weightedLength,lengthAfter:"insertion"===a?null:R.weightedLength,layoutQualityBefore:W,layoutQuality:R}}function ut(t,e,n,o,s,i,a,r,l={}){const c=s,u=t=>r?Math.max(r[0],Math.min(r[1],t)):t;let f=i(u(t.time));const d=i(u(n.time)),g=t.value*c,m=n.value*c,p=e+(t.boundaryOffset??0)*c,h=o+(n.boundaryOffset??0)*c,b=t.sideMassBefore*c,M=n.sideMassAfter*c;let y,x,w,v;"top"===t.side?(y=p-b,x=y+g):(x=p+b,y=x-g),"top"===n.side?(w=h-M,v=w+m):(v=h+M,w=v-m);const k=l.sourceRunwayStart,T=l.minRun,S=(y+x)/2,N=(w+v)/2,O=Math.abs(N-S),P=d-f,F="number"==typeof k&&Number.isFinite(k),A="number"==typeof T&&Number.isFinite(T)&&T>0;if(F&&O>1e-9&&P>0&&("auto"===T||A)){const e="source"===a?.85:"target"===a?.15:.5,n=1.5*Math.min(e*e,(1-e)*(1-e)),o="auto"===T?Math.min(144,Math.sqrt(8*O/n)):T;if(o>P){const e=i(u(Math.min(k,t.time)));if(Number.isFinite(e)){const t=Math.min(f,e);f=Math.min(f,Math.max(t,d-o))}}}const I="source"===a?f+.85*(d-f):"target"===a?f+.15*(d-f):(f+d)/2;return{sx:f,sTop:y,sBot:x,tx:d,tTop:w,tBot:v,cp1X:I,cp2X:I}}function ft(t){return Math.max(18,11*t.length*.58)}function dt(t){const e=1.22*ft(t.labelText)+4;return"start"===t.labelAnchor?[t.labelX,t.labelX+e]:"middle"===t.labelAnchor?[t.labelX-e/2,t.labelX+e/2]:[t.labelX-e,t.labelX]}function gt(t,e){const n=t.labelX-ft(t.labelText),o=e.labelX-ft(e.labelText);return n<=e.labelX+3&&o<=t.labelX+3}function mt(t,e,n){const o=t.map(t=>({...t})),s=new Map;for(const t of o){const n=e[t.id];if(null==n)continue;const o=s.get(n)??[];o.push(t),s.set(n,o)}const i=t=>{if(t.length<2)return;const e=t.reduce((t,e)=>t+e.labelY,0)/t.length,o=(t.length-1)/2;t.forEach((t,s)=>{t.labelY=Math.max(8,Math.min(n-8,e+16*(s-o)))})};for(const t of s.values()){t.sort((t,e)=>t.labelX-e.labelX||t.id.localeCompare(e.id));let e=[],n=-1/0;for(const o of t){const t=o.labelX-ft(o.labelText);e.length>0&&t>n+3&&(i(e),e=[],n=-1/0),e.push(o),n=Math.max(n,o.labelX)}i(e)}return function(t,e){const n=[...t].sort((t,e)=>t.labelY-e.labelY||t.labelX-e.labelX||t.id.localeCompare(e.id));for(let t=0;t<3;t+=1){for(let t=0;t<n.length;t+=1){let e=8;for(let o=0;o<t;o+=1)gt(n[t],n[o])&&(e=Math.max(e,n[o].labelY+16));n[t].labelY=Math.max(n[t].labelY,e)}for(let t=n.length-1;t>=0;t-=1){let o=e-8;for(let e=t+1;e<n.length;e+=1)gt(n[t],n[e])&&(o=Math.min(o,n[e].labelY-16));n[t].labelY=Math.min(n[t].labelY,o)}}}(o,n),o}var pt=/(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?),(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)/gi;function ht(t){return t.replace(pt,(t,e,n)=>`${n},${e}`)}function bt(t){if(!t)return;const e=t=>({x:t.y,y:t.x});return{...t,...t.points&&{points:t.points.map(e)},...t.segments&&{segments:t.segments.map(t=>t.map(e))}}}function Mt(t){return{...t,pathD:ht(t.pathD),y0:t.x0,y1:t.x1,x0:0,x1:0}}function yt(t,e){const n=function(t){if(null==t)return()=>{};const e="function"==typeof t?t:e=>e[t];return t=>xt(e(t))}(e??"value"),o=null==t?void 0:"function"==typeof t?t:e=>e[t];return t=>{const e=o?o(t):void 0;return{value:n(t),category:null==e?void 0:String(e)}}}function xt(t){if("number"==typeof t)return Number.isFinite(t)?t:void 0;if("string"==typeof t&&""!==t.trim()){const e=Number(t);return Number.isFinite(e)?e:void 0}}function wt(t,e,n){const o=t.when;return void 0===o||!0===o||!1!==o&&("function"==typeof o?o(e,n):function(t,e,n){const o=null!=t.axis?n[t.axis]:null!=t.field?e[t.field]:n.value;if(void 0!==t.eq&&o!==t.eq)return!1;if(void 0!==t.ne&&o===t.ne)return!1;if(void 0!==t.in&&!t.in.includes(o))return!1;if(void 0===t.gt&&void 0===t.gte&&void 0===t.lt&&void 0===t.lte&&void 0===t.within&&void 0===t.outside)return!0;const s=xt(o);if(void 0===s)return!1;if(void 0!==t.gt&&!(s>t.gt))return!1;if(void 0!==t.gte&&!(s>=t.gte))return!1;if(void 0!==t.lt&&!(s<t.lt))return!1;if(void 0!==t.lte&&!(s<=t.lte))return!1;if(void 0!==t.within){const[e,n]=t.within;if(!(s>=e&&s<=n))return!1}if(void 0!==t.outside){const[e,n]=t.outside;if(!(s<e||s>n))return!1}return!0}(o,e,n))}import{jsx as vt,jsxs as kt}from"react/jsx-runtime";function Tt(e){const{nodes:o,edges:i,domain:a,plotW:r,plotH:l,ribbonLane:c,ribbonMinRun:u=0,edgeOpacity:f,colorOf:d,layoutOpts:g,orientation:m="horizontal",showLabels:p=!0,labelPriorityAccessor:h,maxLabels:b,selectionDatum:M="raw",styleRules:y,colorBy:x,valueAccessor:w,usageMode:v="static"}=e,k="vertical"===m?l:r,T="vertical"===m?r:l,P=function(t,e,o,s={}){const i=n(s.usageMode??"static"),a=[],r=new Set;for(const e of t)r.has(e.id)&&a.push({kind:"duplicate-node",id:e.id,severity:i.duplicateIds}),r.add(e.id);const l=new Set,c=Array.isArray(o)&&2===o.length,u=c&&Number.isFinite(o[0])&&Number.isFinite(o[1]),f=u&&o[0]<=o[1];c&&u&&f||a.push({kind:"invalid-domain"});for(const e of t)null!=e.xExtent&&(Array.isArray(e.xExtent)&&2===e.xExtent.length&&Number.isFinite(e.xExtent[0])&&Number.isFinite(e.xExtent[1])&&e.xExtent[0]<=e.xExtent[1]||a.push({kind:"invalid-node-time",id:e.id}));for(const t of e)l.has(t.id)&&a.push({kind:"duplicate-edge",id:t.id,severity:i.duplicateIds}),l.add(t.id),r.has(t.source)||a.push({kind:"missing-node",id:t.id,endpoint:"source",nodeId:t.source}),r.has(t.target)||a.push({kind:"missing-node",id:t.id,endpoint:"target",nodeId:t.target}),Number.isFinite(t.startTime)&&Number.isFinite(t.endTime)?((null!=t.systemInTime&&!Number.isFinite(t.systemInTime)||null!=t.systemOutTime&&!Number.isFinite(t.systemOutTime))&&a.push({kind:"invalid-system-time",id:t.id,severity:"warn"}),(!Number.isFinite(t.value)||t.value<=0)&&a.push({kind:"invalid-value",id:t.id}),t.endTime<t.startTime&&a.push({kind:"backward-edge",severity:"fatal",id:t.id,source:t.source,target:t.target})):a.push({kind:"invalid-edge-time",id:t.id});return a}(o,i,a,{usageMode:v}),{fatal:F,warnings:A}=function(t){const e=[],n=[];for(const o of t)"fatal"===s(o)?e.push(o):n.push(o);return{fatal:e,warnings:n}}(P),I=function(t,e,o="static"){if("strip"!==n(o).invalidSystemTime)return t;const s=new Set(e.filter(t=>"invalid-system-time"===t.kind).map(t=>t.id));return 0===s.size?t:t.map(t=>{if(!s.has(t.id))return t;const e={...t};return null==e.systemInTime||Number.isFinite(e.systemInTime)||delete e.systemInTime,null==e.systemOutTime||Number.isFinite(e.systemOutTime)||delete e.systemOutTime,e})}(i,P,v),E=t().domain(a).range([0,k]);if(F.length>0)return{layout:null,layoutConfig:{bands:[],ribbons:[],showLabels:!1!==p},issues:F,warnings:A,xScale:E};const $=ct(o,I,{plotH:T,...g,ribbonLane:c,domain:a}),{centerlines:L,nodeData:B,valueScale:z}=$,C=yt(x,w),X=[],H=[],D=0===u?new Map:function(t,e,n){const o=new Set(e.map(t=>t.target)),s=new Map(t.map(t=>[t.id,t])),i=new Map;for(const t of e){if(o.has(t.source))continue;const e=i.get(t.source)??[];e.push(t),i.set(t.source,e)}const a=new Map;for(const e of t){if(!e.group)continue;const t=a.get(e.group)??[];t.push(e),a.set(e.group,t)}const r=new Set;for(const[t,e]of a){const n=e.flatMap(t=>i.get(t.id)??[]),s=new Set(n.map(t=>t.startTime));n.length>0&&1===s.size&&e.every(t=>{const e=t.xExtent?.[0],s=n[0].startTime;return!o.has(t.id)&&(i.get(t.id)?.length??0)>0&&Number.isFinite(e)&&e<s})&&r.add(t)}const l=new Map;for(const[t,e]of i){const o=s.get(t);if(o?.group&&!r.has(o.group))continue;const i=o?.xExtent?.[0],a=[...e].sort((t,e)=>t.startTime-e.startTime||t.id.localeCompare(e.id)),c=a[0]?.startTime-1;let u=null;for(let t=0;t<a.length;){const e=a[t].startTime;let o=t+1;for(;o<a.length&&a[o].startTime===e;)o++;for(let e=t;e<o;e++){const t=a[e],o=Number.isFinite(i)&&i<t.startTime,s=Number.isFinite(t.systemInTime)&&t.systemInTime<t.startTime;if(!o&&!s)continue;let r=n[0];o&&(r=Math.max(r,i)),s&&(r=Math.max(r,t.systemInTime)),!o&&s&&Number.isFinite(c)&&(r=Math.max(r,c)),null!=u&&(r=Math.max(r,u)),r<t.startTime&&l.set(t.id,r)}u=e,t=o}}for(const[t,e]of a){if(!r.has(t))continue;const n=e.flatMap(t=>i.get(t.id)??[]);if(!n.every(t=>l.has(t.id))){for(const t of n)l.delete(t.id);continue}const o=Math.max(...n.map(t=>l.get(t.id)));for(const t of n)l.set(t.id,o)}return l}(o,I,a),j=new Map(o.filter(t=>t.group).map(t=>[t.id,t.group])),Y=new Map;for(const t of I){const e=B[t.source]?.localAttachments.get(t.id),n=B[t.target]?.localAttachments.get(t.id);e&&n&&Y.set(t.id,ut(e,L[t.source],n,L[t.target],z,E,c,a,{minRun:u,sourceRunwayStart:D.get(t.id)}))}const q=function(t,e,n,o,s,i){const a=new Map(e),r=new Map;for(const e of t){const t=i?.get(e.source),n=null==t?`node:${e.source}`:`group:${t}`,o=r.get(n)??new Map,s=o.get(e.startTime)??[];s.push(e),o.set(e.startTime,s),r.set(n,o)}for(const t of r.values())for(const[i,r]of t){if(!r.some(t=>n.has(t.id)))continue;const t=r.map(t=>e.get(t.id));if(t.some(t=>null==t))continue;const l=o(i),c=Math.min(...t.map(t=>t.sx));if(!(c<l-1e-9))continue;const u=Math.max(...r.map(t=>{const e=n.get(t.id);return null==e?l:Math.min(l,o(e))})),f=Math.min(l,Math.max(c,u));for(const t of r){const n=e.get(t.id),o="source"===s?.85:"target"===s?.15:.5,i=f+(n.tx-f)*o;a.set(t.id,{...n,sx:f,cp1X:i,cp2X:i})}}return a}(I,Y,D,E,c,j),V=function(t,e,n,o,s){const i=new Map;for(const a of t){if(!n.has(a.id))continue;const t=e.get(a.id);if(!(t&&t.sx<o(a.startTime)-1e-9))continue;const r=s(t.sx);Number.isFinite(r)&&r<a.startTime&&i.set(a.id,r)}return i}(I,q,D,E,t=>a[0]+t/k*(a[1]-a[0])),U=function(t,e,n){const o=new Map,s=new Map;for(const[t,e]of n??[]){const n=s.get(e)??[];n.push(t),s.set(e,n)}for(const i of t){const t=e.get(i.id);if(!(null!=t&&Number.isFinite(t)&&t<i.startTime))continue;const a=n?.get(i.source),r=null==a?[i.source]:s.get(a)??[i.source];for(const e of r){const n=o.get(e)??new Map,s=n.get(i.startTime);n.set(i.startTime,null==s?t:Math.min(s,t)),o.set(e,n)}}return o}(I,V,j);o.forEach((t,e)=>{const n=B[t.id];if(!n||0===n.samples.length)return;const o=(s=n.samples,(i=U.get(t.id))&&0!==i.size?s.map(t=>{const e=i.get(t.t);return null==e?t:{...t,t:e}}):s);var s,i;const r=function(t,e,n,o,s){if(0===t.length)return null;const i=N(t,s),a=t=>e+(i[t].boundaryOffset??0)*n,r=t=>a(t)-i[t].topMass*n,l=t=>a(t)+i[t].botMass*n;let c=`M${o(i[0].t)},${r(0)}`;for(let t=1;t<i.length;t++)c+=` L${o(i[t].t)},${r(t)}`;c+=` L${o(i[i.length-1].t)},${l(i.length-1)}`;for(let t=i.length-2;t>=0;t--)c+=` L${o(i[t].t)},${l(t)}`;return c+" Z"}(o,L[t.id],z,E,a);if(!r)return;const l=N(o,a),c=l.find(t=>t.topMass+t.botMass>0)||l[0],u=(c.botMass-c.topMass+2*(c.boundaryOffset??0))*z/2,f=L[t.id]+u;let g,p,h=d(t.id,e),b=h,M=.5;const x=t.__raw??t;if(y&&y.length>0){const t=function(t,e,n){if(!e||0===e.length)return{};let o={};for(const s of e){if(!wt(s,t,n))continue;const e="function"==typeof s.style?s.style(t,n):s.style;e&&(o={...o,...e})}return o}(x,y,C(x));"string"==typeof t.fill?h=t.fill:null!=t.fill&&("object"==typeof(w=t.fill)&&null!==w&&"hatch"===w.type)&&(p=t.fill,h=t.fill.background&&"transparent"!==t.fill.background?t.fill.background:h),"string"==typeof t.stroke&&(b=t.stroke),"number"==typeof t.strokeWidth&&(M=t.strokeWidth),"number"==typeof t.fillOpacity&&(g=t.fillOpacity),"number"==typeof t.opacity&&null==g&&(g=t.opacity)}var w;const v=function(t,e,n,o,s,i){const a=n.nodeData[t];if(!a||0===a.samples.length)return[];const r=n.valueScale,l=n.centerlines[t],c=N(a.samples,s),u=c.find(t=>t.topMass+t.botMass>0)||c[0],f=[...c].reverse().find(t=>t.topMass+t.botMass>0)||c[c.length-1],d=o(u.t),g=o(f.t),m=t=>o(S(t,s)),p=[],h=(t,e,n,o)=>`M${t},${e} L${n},${e} L${n},${o} L${t},${o} Z`;for(const n of e){if(n.source===t&&null!=n.systemInTime&&Number.isFinite(n.systemInTime)){const t=a.localAttachments.get(n.id),e=i?.get(n.id)??n.startTime;if(t&&"out"===t.kind&&n.systemInTime<e){const o=m(n.systemInTime),i=m(e),a=null!=s&&n.systemInTime<s[0],c=a?o:o-20,u=a?Math.min(i,o+20):o,f=Math.max(d,c);if(i>f){const[e,n]=O(t,l,r);p.push({pathD:h(f,e,i,n),x0:c,x1:u,from:0,to:1})}}}if(n.target===t&&null!=n.systemOutTime&&Number.isFinite(n.systemOutTime)){const t=a.localAttachments.get(n.id);if(t&&"in"===t.kind&&n.systemOutTime>n.endTime){const e=m(n.systemOutTime),o=m(n.endTime),s=e+20,i=Math.min(g,s);if(i>o){const[n,a]=O(t,l,r);p.push({pathD:h(o,n,i,a),x0:e,x1:s,from:1,to:0})}}}}return p}(t.id,I,$,E,a,V);X.push({id:t.id,pathD:r,fill:h,stroke:b,strokeWidth:M,...null!=g&&{fillOpacity:g},...p&&{hatchFill:p},...v.length>0&&{gradientStubs:v},rawDatum:x,labelX:E("vertical"===m&&t.xExtent?t.xExtent[0]:c.t)-4,labelY:f,labelText:t.label??t.id})});const W=new Map;o.forEach((t,e)=>W.set(t.id,e)),I.forEach(t=>{const e=q.get(t.id);if(!e)return;const n=W.get(t.source)??0,o=d(t.source,n),{pathD:s,bezier:i}=function(t){const{sx:e,sTop:n,sBot:o,tx:s,tTop:i,tBot:a,cp1X:r,cp2X:l}=t,c=(n+o)/2,u=(i+a)/2;return{pathD:[`M${e},${n}`,`C${r},${n} ${l},${i} ${s},${i}`,`L${s},${a}`,`C${l},${a} ${r},${o} ${e},${o}`,"Z"].join(" "),bezier:{circular:!1,points:[{x:e,y:c},{x:r,y:c},{x:l,y:u},{x:s,y:u}],halfWidth:(o-n)/2}}}(e),a=t.__raw??t,r="function"==typeof f?Number(f(a)):f,l=Number.isFinite(r)?Math.max(0,Math.min(1,r)):.35;H.push({id:t.id,pathD:s,fill:o,opacity:l,rawDatum:a,bezier:i})});const R=mt(X,$.slotByNode,T).map(t=>function(t,e){return"horizontal"===e?t:{...t,pathD:ht(t.pathD),gradientStubs:t.gradientStubs?.map(Mt),labelX:t.labelY,labelY:t.labelX,labelAnchor:"middle",labelBaseline:"auto"}}(t,m)),_="vertical"===m?function(t,e,n){const o=t.map(t=>({...t}));for(const t of o){const n=1.22*ft(t.labelText)+4;t.labelX=n>=e-4?e/2:Math.max(n/2+2,Math.min(e-n/2-2,t.labelX))}const s=[],i=[...o].sort((t,e)=>t.labelY-e.labelY||t.labelX-e.labelX);for(const t of i){const e=s[s.length-1];!e||Math.abs(e[0].labelY-t.labelY)>14?s.push([t]):e.push(t)}for(const t of s){t.sort((t,e)=>t.labelX-e.labelX||t.id.localeCompare(e.id));const e=[],o=new Map;for(const n of t){const[t,s]=dt(n);let i=e.findIndex(e=>t>e+8);-1===i&&(i=e.length),e[i]=s,o.set(n,i)}const s=t.reduce((t,e)=>t+e.labelY,0)/t.length,i=s<14*e.length+8;for(const e of t){const t=o.get(e)??0;e.labelY=i?Math.min(n-8,12+14*t):Math.max(8,s-14*t)}}return o}(R,r,l):R,G=new Map;if(null!=h)for(const t of o){const e=t.__raw??t,n="function"==typeof h?h(e):Number(e[h]);Number.isFinite(n)&&G.set(t.id,n)}const Z=function(t,e,n,o,s={}){if(!1===o)return t.map(t=>({...t,labelText:"",labelDeferred:!1,labelFullText:void 0}));if(!0===o)return t.map(t=>({...t,labelDeferred:!1,labelFullText:void 0}));const i=Math.max(1,e*n);let a=Math.max(4,Math.min(t.length,Math.floor(i/14e3)));Number.isFinite(s.maxLabels)&&s.maxLabels>=0&&(a=Math.min(a,Math.floor(s.maxLabels)));const r=t.map((t,e)=>{const n=s.priorityById?.get(t.id),o=Math.abs(t.labelY);return{band:t,index:e,score:null!=n&&Number.isFinite(n)?1e6*n+ft(t.labelText):ft(t.labelText)+.01*o}}).filter(t=>t.band.labelText.trim().length>0).sort((t,e)=>e.score-t.score||t.index-e.index||t.band.id.localeCompare(e.band.id)),l=new Set(r.slice(0,a).map(t=>t.band.id));return t.map(t=>l.has(t.id)||0===t.labelText.trim().length?{...t,labelDeferred:!1,labelFullText:void 0}:{...t,labelFullText:t.labelText,labelText:"",labelDeferred:!0})}(_,r,l,p,{...G.size>0&&{priorityById:G},...null!=b&&{maxLabels:b}});return{layout:$,layoutConfig:{bands:Z,ribbons:H.map(t=>function(t,e){return"horizontal"===e?t:{...t,pathD:ht(t.pathD),bezier:bt(t.bezier)}}(t,m)),showLabels:!1!==p,selectionDatum:M},issues:[],warnings:A,xScale:E}}self.onmessage=t=>{const e=t.data,n=e?.requestId,o=e?.request??e;try{const t=o.colorById??{},e=o.fallbackPalette??["#475569"],a=(n,o)=>t[n]??e[o%e.length]??"#475569",r=Tt({...o.input,colorOf:a});self.postMessage({requestId:n,layout:(i=r.layout,i?{...i,sides:i.sides instanceof Map?[...i.sides.entries()]:i.sides}:null),layoutConfig:(s=r.layoutConfig,{bands:(s.bands??[]).map(({rawDatum:t,...e})=>e),ribbons:(s.ribbons??[]).map(({rawDatum:t,...e})=>e),showLabels:s.showLabels}),issues:r.issues,warnings:r.warnings,domain:o.input.domain,timelineExtent:"vertical"===o.input.orientation?o.input.plotH:o.input.plotW})}catch(t){self.postMessage({requestId:n,error:{message:t instanceof Error?t.message:String(t),name:t instanceof Error?t.name:"Error",stack:t instanceof Error?t.stack:void 0}})}var s,i};
|