Module

Hylograph.ForceEngine.Setup.WASM

Package
purescript-hylograph-simulation
Repository
afcondon/purescript-hylograph-simulation

WASM Force Setup

Declarative force configuration for WASM simulation engine. Uses the same Setup types as the default engine, and means the same.

What a Setup means here, force by force, is what it means to the default engine (Hylograph.ForceEngine.Setup.applySetup), and test/engine-parity.mjs holds the two to each other:

  • any number of forces of any type; a later force replaces an earlier one of the same name, and each tick applies them in name order (the default engine keeps them in a Map keyed by name);
  • links name their endpoints by node id, not by array position;
  • new nodes are initialized as d3 initializes them (Hylograph.ForceEngine.Core.initializeNodes).

Dynamic values, filters, groups and regions are evaluated once per node (or per link) when the setup is applied and handed to the kernel as arrays; the kernel never calls back into JavaScript.

Both engines are deterministic: the same nodes, links and setup give the same positions on every run. The kernel computes in f32 and the default engine in f64, so the two agree to float width over one tick and drift apart after that, as any two roundings of a force layout do.

The nodes a caller is handed (getNodes, step) are fresh records after every tick, not the same objects moved, which is the one way this engine differs from the default one. A pin set on the latest ones (node.fx, as a drag does) is read before the next tick.

Example:

import Hylograph.ForceEngine.Setup (setup, manyBody, center, withStrength, static)
import Hylograph.ForceEngine.Setup.WASM as WASM

mySetup = setup "physics"
  [ manyBody "charge" # withStrength (static (-30.0))
  , center "center" # withX (static 0.0) # withY (static 0.0)
  ]

main = do
  WASM.initWasm "./pkg/force_kernel.js"
  sim <- WASM.create initialNodes initialLinks
  result <- WASM.applySetupWithData mySetup newNodes newLinks sim
  -- Use result.nodes.entered, result.nodes.exited for animations

#WASMSim Source

type WASMSim :: Row Type -> Typetype WASMSim r = { forceIds :: Ref (Map String ForceId), linksRef :: Ref (Array { source :: Int, target :: Int }), nodesRef :: Ref (Array (SimulationNode r)), wasmSim :: WASMSimulation }

WASM Simulation handle. Wraps the low-level WASM handle with PureScript state management.

#initWasm Source

initWasm :: String -> Aff Unit

Initialize the WASM module. Call once at application startup.

#isWasmReady Source

isWasmReady :: Effect Boolean

Check if WASM is initialized

#create Source

create :: forall r. Array (SimulationNode r) -> Array { source :: Int, target :: Int } -> Effect (WASMSim r)

Create a WASM simulation with initial nodes and links.

#createEmpty Source

createEmpty :: forall r. Effect (WASMSim r)

Create an empty WASM simulation (for use with applySetupWithData)

#free Source

free :: forall r. WASMSim r -> Effect Unit

Free WASM simulation memory

#applySetup Source

applySetup :: forall r. Setup (SimulationNode r) -> WASMSim r -> Effect Unit

Apply a Setup to a WASM simulation.

Maps declarative force configuration to WASM kernel calls: the kernel's force list is emptied and refilled from the setup, so this is idempotent and can be called repeatedly with different setups. Dynamic values and filters are evaluated against the simulation's current nodes; apply the setup again after changing what they read.

See the module header for how this compares with the default engine.

#tryApplySetup Source

tryApplySetup :: forall r. Setup (SimulationNode r) -> WASMSim r -> Effect (Either String Unit)

applySetup, with the one thing that can go wrong as a value, as the default engine's tryApplySetup has it: Left "node not found: <id>" where the setup has a force along the links and a link names a node that is not among the nodes. The simulation is then left as it was.

#applySetupWithData Source

applySetupWithData :: forall r. Setup (SimulationNode r) -> Array (SimulationNode r) -> Array { source :: Int, target :: Int } -> WASMSim r -> Effect { links :: GUPLinkResult (), nodes :: GUPResult (SimulationNode r) }

Apply setup with new nodes and links, using GUP semantics.

This provides functional parity with the default engine's applySetupWithData:

  1. Force configuration (via applySetup)
  2. Node GUP: diff desired vs current, preserve simulation state
  3. Link GUP: diff desired vs current

Simulation state preserved for updated nodes:

  • x, y: Current position
  • vx, vy: Current velocity
  • fx, fy: Pinned position

Example:

result <- applySetupWithData mySetup newNodes newLinks sim
animateEnter result.nodes.entered
animateExit result.nodes.exited
reheat sim

#retarget Source

retarget :: forall r. String -> (SimulationNode r -> Maybe { x :: Number, y :: Number }) -> WASMSim r -> Effect Boolean

Give a Towards force new targets, by the name it has in the setup, without re-applying the setup. Cheap enough to call every tick: one array goes to the kernel and overwrites the old targets in place. For morphing between layouts. False if the setup has no Towards force of that name.

#retargetTo Source

retargetTo :: forall r. String -> Array { x :: Number, y :: Number } -> WASMSim r -> Effect Boolean

retarget with the points themselves, one for each node in the order of the simulation's nodes (getNodes). A node past the end of the array is left alone by the force.

#reradius Source

reradius :: forall r. String -> (SimulationNode r -> Number) -> WASMSim r -> Effect Boolean

Give a Collide, Radial or Contain force new radii, by the name it has in the setup, without re-applying the setup. Cheap enough to call every tick. For a collision that grows in as nodes arrive, or shrinks to let them pass. False if the setup has no such force of that name.

#snapshot Source

snapshot :: forall r. WASMSim r -> Effect Snapshot

Record everything that changes as the simulation runs: positions, velocities, pins, alpha and the other parameters, and the state of the stream that separates coincident nodes.

#restore Source

restore :: forall r. Snapshot -> WASMSim r -> Effect Boolean

Put the simulation back in a recorded state: with the same setup and links, the ticks that follow are exactly the ticks that followed the snapshot. False, changing nothing, if the snapshot does not fit (it was taken with a different number of nodes, or is malformed).

#kineticEnergy Source

kineticEnergy :: forall r. WASMSim r -> Effect Number

Kinetic energy after the last tick (unit mass per node). Falls toward 0 as the layout settles.

#maxDisplacement Source

maxDisplacement :: forall r. WASMSim r -> Effect Number

The furthest any node moved during the last tick.

#maxAcceleration Source

maxAcceleration :: forall r. WASMSim r -> Effect Number

The largest change in any node's step between the last two ticks: the acceleration it actually underwent.

This is what kineticEnergy and maxDisplacement cannot see. A node on a spring is momentarily still at the far end of every swing, and nodes released together swing in step, so both of those vanish there, far from rest. The acceleration is then at its largest. 0 until two ticks have been made since the simulation was created, restored or resized.

#settled Source

settled :: forall r. { acceleration :: Number, step :: Number } -> WASMSim r -> Effect Boolean

Is the simulation at rest? True when, over the last two ticks, no node moved further than step in a tick and no node's step changed by more than acceleration. False until two ticks have been made.

It is measured from positions, so it is right whatever moved a node, and a node held against a hard region by a force that keeps pushing counts as at rest. It says what the last two ticks did: after retarget, tick before asking.

For a node on a spring of stiffness k (a towards of that strength, at alpha 1) with velocity retention r, the node is then within (acceleration + (1 - r) * (step + acceleration)) / (k * r) of where it will stop, and gets no further away. Stop on the first tick it is true.

#step Source

step :: forall r. WASMSim r -> Effect (Array (SimulationNode r))

Run a single simulation tick and return the nodes where it left them. (tick returns the new alpha; tick followed by getNodes copies the positions out of the kernel twice.)

#tick Source

tick :: forall r. WASMSim r -> Effect Number

Run a single simulation tick. Returns new alpha value.

#tickN Source

tickN :: forall r. Int -> WASMSim r -> Effect Number

Run multiple ticks. Returns final alpha.

#getNodes Source

getNodes :: forall r. WASMSim r -> Effect (Array (SimulationNode r))

The nodes as the last tick (or the last change made through this module) left them. The same records until the next tick, so a pin set on one of them is seen by that tick.

#getAlpha Source

getAlpha :: forall r. WASMSim r -> Effect Number

Get current alpha value

#reheat Source

reheat :: forall r. WASMSim r -> Effect Unit

Reheat simulation (set alpha to 1.0)

#isRunning Source

isRunning :: forall r. WASMSim r -> Effect Boolean

Check if simulation is still running

#pinNodes Source

pinNodes :: forall r. WASMSim r -> Effect Unit

Pin every node where it is (fx = x, fy = y), on the nodes and in the kernel.

#unpinNodes Source

unpinNodes :: forall r. WASMSim r -> Effect Unit

Unpin every node, on the nodes and in the kernel.

#interpolatePositions Source

interpolatePositions :: forall r. PositionMap -> PositionMap -> Number -> WASMSim r -> Effect Unit

Put every node that both maps name at start + (target - start) * progress, on the nodes and in the kernel, so that the next tick goes on from there. Velocities and pins are left as they are.

Re-exports from Hylograph.ForceEngine.Setup

#Value Source

data Value node a

A value that is one constant, or computed from each element it applies to: Value node a per node, Value (LinkEnds node) a per link.

Constructors

#SetupParams Source

type SetupParams = { alpha :: Number, alphaDecay :: Number, alphaMin :: Number, alphaTarget :: Number, velocityRetention :: Number }

Simulation parameters

#Setup Source

type Setup node = { forces :: Array (ForceConfig node), name :: String, params :: SetupParams }

Complete setup: forces + simulation params

#NodeGUPInternal Source

type NodeGUPInternal node = { entered :: Array node, exited :: Array node, merged :: Array node, updated :: Array node }

Internal result type that includes the merged array

#GUPResult Source

type GUPResult node = { entered :: Array node, exited :: Array node, updated :: Array node }

Result of a node data update with enter/update/exit categorization

  • entered: Nodes newly added to simulation (use for enter animations)
  • updated: Existing nodes that were modified (simulation state preserved)
  • exited: Nodes removed from simulation (use for exit animations)

#GUPLinkResult Source

type GUPLinkResult :: Row Type -> Typetype GUPLinkResult linkRow = { entered :: Array { source :: NodeID, target :: NodeID | linkRow }, exited :: Array { source :: NodeID, target :: NodeID | linkRow }, updated :: Array { source :: NodeID, target :: NodeID | linkRow } }

Result of a link data update with enter/update/exit categorization Links are keyed by (source, target) pair

#ForceConfig Source

data ForceConfig node

Configuration for a single force: one constructor per kind of force, each with a record of that force's own parameters. Parameterized by node type for dynamic values and filters.

#valueToNumber Source

valueToNumber :: forall node. Value node Number -> Number

Extract a number from a Value (for static values only, dynamic returns default) Used internally; prefer the accessor pattern for dynamic values

#getParams Source

getParams :: forall node. Setup node -> SetupParams

Get params from setup

#getForces Source

getForces :: forall node. Setup node -> Array (ForceConfig node)

Get forces from setup

#computeNodeGUP Source

computeNodeGUP :: forall row. Array (SimulationNode row) -> Array (SimulationNode row) -> NodeGUPInternal (SimulationNode row)

Compute node GUP: which nodes are entering, updating, exiting For updates, merge simulation state (x, y, vx, vy, fx, fy) from current into desired

#computeLinkGUP Source

computeLinkGUP :: forall linkRow. Array { source :: NodeID, target :: NodeID | linkRow } -> Array { source :: NodeID, target :: NodeID | linkRow } -> GUPLinkResult linkRow

Compute link GUP: which links are entering, updating, exiting Links are keyed by (source, target) pair

Re-exports from Hylograph.ForceEngine.Simulation

#SimulationNode Source

type SimulationNode :: Row Type -> Typetype SimulationNode r = Record (D3_ID + D3_XY + D3_VxyFxy + r)

A simulation node with all required fields for force simulation and transitions. Extends user data row with id, position (x/y), velocity (vx/vy), and fixed position (fx/fy).

Example:

type MyNode = SimulationNode (name :: String, group :: Int)
-- Expands to: { id :: Int, x, y, vx, vy, fx, fy, name :: String, group :: Int }