Hylograph.ForceEngine.Setup
- Package
- purescript-hylograph-simulation
- Repository
- afcondon/purescript-hylograph-simulation
Declarative Force Setup
Unified system for declaratively configuring force simulations. Replaces the older ForceSpec (too simple) and Config.* modules (wrong abstraction layer).
Key features:
- Static or dynamic (per-node, or per-link) parameter values
- Optional filters to apply forces selectively
- Idempotent
applySetupthat works for both initial setup and updates
Example:
mySetup = setup "physics"
[ manyBody "charge" # withStrength (static (-30.0))
, collide "collision" # withRadius (dynamic _.r)
, positionX "gridX" # withX (dynamic _.gridX) # withStrength (static 0.1)
, positionY "gridY" # withY (dynamic _.gridY) # withStrength (static 0.1)
]
-- Apply to simulation (idempotent - can call repeatedly)
applySetup mySetup sim
-- Update: just call applySetup with new config
applySetup (mySetup # removeForce "charge") sim
A force is one constructor of ForceConfig, carrying a record of exactly
the parameters that force has. The smart constructors (manyBody,
collide, ...) and the with... builders are the intended way to make
one; a builder that does not apply to a force leaves it unchanged.
Seven forces are d3-force's. Five are not (towards, rectCollide,
contain, cohesion, directional), nor is a many-body force scoped
by group, nor a collision with a filter or scaled by alpha. Both engines
run all of them: applySetup here is the default engine
(hylograph-forces, PureScript, no D3), and
Hylograph.ForceEngine.Setup.WASM.applySetup is the Rust/WASM kernel.
#valueToNumber Source
valueToNumber :: forall node. Value node Number -> NumberExtract a number from a Value (for static values only, dynamic returns default) Used internally; prefer the accessor pattern for dynamic values
#LinkStrength Source
data LinkStrength nodeHow strong each link's spring is.
Constructors
LinkStrength (Value (LinkEnds node) Number)ByDegreed3-force's own default: 1 / min(links at the source, links at the target), so that heavily linked nodes are not pulled apart.
#ForceType Source
data ForceTypeForce type enumeration
Constructors
ForceManyBodyForceCollideForceLinkForceCenterForcePositionXForcePositionYForceRadialForceTowardsForceRectCollideForceContainForceCohesionForceDirectional
Instances
#ForceConfig Source
data ForceConfig nodeConfiguration 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.
Constructors
ManyBodyForce (ManyBodyConfig node)CollideForce (CollideConfig node)LinkForce (LinkConfig node)CenterForce CenterConfigPositionXForce (PositionConfig node)PositionYForce (PositionConfig node)RadialForce (RadialConfig node)TowardsForce (TowardsConfig node)RectCollideForce (RectCollideConfig node)ContainForce (ContainConfig node)CohesionForce (CohesionConfig node)DirectionalForce (DirectionalConfig node)
#ManyBodyConfig Source
type ManyBodyConfig node = { distanceMax :: Number, distanceMin :: Number, filter :: Maybe (node -> Boolean), name :: String, scope :: ManyBodyScope node, strength :: Value node Number, theta :: Number }Charge: every node repels (negative) or attracts (positive) every other.
#ManyBodyScope Source
data ManyBodyScope nodeWhich pairs of nodes a many-body force acts between. A node whose group
is Nothing is in no group: it has no same-group pairs, and is in a
different group from everyone.
Constructors
AllPairsWithinGroups (node -> Maybe Int)BetweenGroups (node -> Maybe Int)
#CollideConfig Source
type CollideConfig node = { alphaScaled :: Boolean, filter :: Maybe (node -> Boolean), iterations :: Int, name :: String, radius :: Value node Number, strength :: Number }Circles that must not overlap.
A node the filter leaves out collides with nothing. With alphaScaled the strength used is
strength * alpha, so the collision weakens as the simulation cools and
gives way to forces that hold a node at a place; without it (d3's
collide) a collision is as hard at rest as in flight.
#LinkConfig Source
type LinkConfig node = { distance :: Value (LinkEnds node) Number, iterations :: Int, name :: String, strength :: LinkStrength node }Springs along the simulation's links.
#CenterConfig Source
type CenterConfig = { name :: String, strength :: Number, x :: Number, y :: Number }Move the mean position of all nodes toward a point.
#TowardsConfig Source
type TowardsConfig node = { filter :: Maybe (node -> Boolean), name :: String, strength :: Value node Number, target :: node -> Maybe { x :: Number, y :: Number } }A spring from each node to its own target point:
v += (target - position) * strength * alpha. Nothing leaves a node
alone. For morphing between layouts: on the WASM engine the targets can
be replaced between ticks without re-applying the setup
(Hylograph.ForceEngine.Setup.WASM.retarget); on the default engine,
apply the setup again.
#RectCollideConfig Source
type RectCollideConfig node = { filter :: Maybe (node -> Boolean), halfHeight :: Value node Number, halfWidth :: Value node Number, iterations :: Int, name :: String, scope :: ManyBodyScope node, strength :: Number, throughSqueeze :: Boolean }Axis-aligned rectangles (for labels) that must not
overlap: an overlapping pair is pushed apart along the axis on which it
overlaps least, the larger rectangle moving less. A pinned rectangle
(fx, fy) is never moved, and what overlaps it takes the whole push.
A node the filter leaves out collides with nothing. scope restricts
the pairs by group: only two nodes of the same group, or only two nodes
not of the same group (labels against dots, say, and not each other).
throughSqueeze: a rectangle pushed from both sides on an axis goes
through one of them instead of staying where the pushes cancel (the way
it is already moving, else with the stronger side). That is what
resolves crowded wide rectangles, and it wants nothing else pressing
them together: under a pull that does not die away, a rectangle is
walked through its neighbour. The rule in full is on
Hylograph.Forces.RectCollide.
#ContainConfig Source
type ContainConfig node = { halfHeight :: Value node Number, halfWidth :: Value node Number, hard :: Boolean, name :: String, radius :: Value node Number, region :: node -> Maybe Int, regions :: Array Region, strength :: Number }Keep nodes inside regions. Each node is confined to
regions !! i where region node == Just i (Nothing: free). What is
kept inside is the node's body: a rectangle of halfWidth by
halfHeight grown all round by radius (a circle when the half-extents
are 0, as they are by default; in a circular region a rectangle counts
as the circle round it). strength (0 to 1) steers a node that is
about to leave back toward the nearest allowed point; hard also clamps
positions into the region after each tick, so that no node is ever
drawn outside.
#Region Source
data RegionA region nodes can be confined to.
Constructors
RectRegion { x0 :: Number, x1 :: Number, y0 :: Number, y1 :: Number }CircleRegion { radius :: Number, x :: Number, y :: Number }PolygonRegion (Array { x :: Number, y :: Number })Convex, vertices in either winding.
#DirectionalConfig Source
type DirectionalConfig node = { axis :: { x :: Number, y :: Number }, gap :: Value (LinkEnds node) Number, hard :: Boolean, iterations :: Int, name :: String, strength :: Value (LinkEnds node) Number }Over the simulation's links: push each link's target
to be at least gap beyond its source along axis (children below
parents, with axis (0, 1)). Links already that far apart are left alone.
As a force it is scaled by alpha and shared with everything else that
pushes, so the gap it leaves can be well short of the one asked for.
With hard the links are also projected after each tick, so that the
gap asked for is the gap kept: a link short of its gap moves its target
along the axis by the shortfall (its source back, if the target is
pinned and the source is not).
#forceName Source
forceName :: forall node. ForceConfig node -> StringGet the name of a force config
#forceType Source
forceType :: forall node. ForceConfig node -> ForceTypeWhich kind of force a config is
#manyBody Source
manyBody :: forall node. String -> ForceConfig nodeCreate a many-body (charge) force Default: repulsive with strength -30
#collide Source
collide :: forall node. String -> ForceConfig nodeCreate a collision force Default: radius 1, strength 1
#link Source
link :: forall node. String -> ForceConfig nodeCreate a link (spring) force Default: distance 30, strength 1
#center Source
center :: forall node. String -> ForceConfig nodeCreate a centering force Default: center at (0, 0), strength 1
#positionX Source
positionX :: forall node. String -> ForceConfig nodeCreate an X-positioning force Default: x = 0, strength 0.1
#positionY Source
positionY :: forall node. String -> ForceConfig nodeCreate a Y-positioning force Default: y = 0, strength 0.1
#radial Source
radial :: forall node. String -> ForceConfig nodeCreate a radial force Default: radius 100, center (0,0), strength 0.1
#rectCollide Source
rectCollide :: forall node. String -> ForceConfig nodeCreate a rectangle collision force. Default: half-width 1, half-height 1, strength 1, 1 iteration, every pair, a squeezed rectangle stays put.
#contain Source
contain :: forall node. String -> Region -> ForceConfig nodeCreate a containment force keeping every node in one region. Default: radius 0, strength 1, with the hard limit on. For
several regions use withRegions and withRegion.
#containEach Source
containEach :: forall node. String -> Array Region -> (node -> Maybe Int) -> ForceConfig nodeCreate a containment force keeping each node in a region of its own:
node n in regions !! i where region n == Just i, and
free where it is Nothing. Defaults as contain.
#cohesion Source
cohesion :: forall node. String -> (node -> Maybe Int) -> ForceConfig nodeCreate a group cohesion force. Default: strength 0.1.
#directional Source
directional :: forall node. String -> ForceConfig nodeCreate a directional link constraint.
Default: gap 30 along (0, 1) (targets below sources), strength 1, soft
(withHardLimit true makes the gap exact).
#withStrength Source
withStrength :: forall node. Value node Number -> ForceConfig node -> ForceConfig nodeSet strength.
Per node (dynamic) for ManyBody, PositionX/Y, Radial, Towards and
Cohesion. Collide, Center, RectCollide and Contain have one strength: a
static sets it, a dynamic is ignored. For Link and Directional a
static sets every link's strength and a dynamic, being a function of
a node, is ignored: use withLinkStrength.
#withRadius Source
withRadius :: forall node. Value node Number -> ForceConfig node -> ForceConfig nodeSet radius (Collide and Radial; the node's own radius for Contain)
#withX Source
withX :: forall node. Value node Number -> ForceConfig node -> ForceConfig nodeSet X: the target of PositionX (per node if dynamic), or the centre of
Center and Radial (static only).
#withY Source
withY :: forall node. Value node Number -> ForceConfig node -> ForceConfig nodeSet Y: the target of PositionY (per node if dynamic), or the centre of
Center and Radial (static only).
#withDistance Source
withDistance :: forall node. Value node Number -> ForceConfig node -> ForceConfig nodeSet every link's distance (for Link; static only: a dynamic here is
a function of a node and is ignored, use withLinkDistance).
#withTheta Source
withTheta :: forall node. Number -> ForceConfig node -> ForceConfig nodeSet theta (Barnes-Hut approximation, for ManyBody)
#withIterations Source
withIterations :: forall node. Int -> ForceConfig node -> ForceConfig nodeSet iterations (for Collide, Link, RectCollide, Directional)
#withFilter Source
withFilter :: forall node. (node -> Boolean) -> ForceConfig node -> ForceConfig nodeAdd a filter predicate: the force only applies to matching nodes. For ManyBody (a filtered-out node exerts no charge but is still pushed), Collide and RectCollide (a filtered-out node collides with nothing), PositionX, PositionY, Radial, Towards and Cohesion.
#withDistanceMin Source
withDistanceMin :: forall node. Number -> ForceConfig node -> ForceConfig nodeSet distance min (for ManyBody)
#withDistanceMax Source
withDistanceMax :: forall node. Number -> ForceConfig node -> ForceConfig nodeSet distance max (for ManyBody)
#withLinkDistance Source
withLinkDistance :: forall node. Value (LinkEnds node) Number -> ForceConfig node -> ForceConfig nodeSet link distance per link, from the nodes at its two ends (for Link)
#withLinkStrength Source
withLinkStrength :: forall node. Value (LinkEnds node) Number -> ForceConfig node -> ForceConfig nodeSet strength per link, from the nodes at its two ends (Link, Directional)
#withDegreeStrength Source
withDegreeStrength :: forall node. ForceConfig node -> ForceConfig nodeGive links d3-force's default strength, 1 / min(links at the source, links at the target) (for Link)
#withTarget Source
withTarget :: forall node. (node -> Maybe { x :: Number, y :: Number }) -> ForceConfig node -> ForceConfig nodeSet each node's target point (for Towards)
#withAlphaScaling Source
withAlphaScaling :: forall node. Boolean -> ForceConfig node -> ForceConfig nodeMake a collision's strength follow alpha, so that it yields as the simulation cools (for Collide). Off by default.
#withHalfWidth Source
withHalfWidth :: forall node. Value node Number -> ForceConfig node -> ForceConfig nodeSet the rectangles' half-width (for RectCollide; the half-width of the node's body for Contain)
#withHalfHeight Source
withHalfHeight :: forall node. Value node Number -> ForceConfig node -> ForceConfig nodeSet the rectangles' half-height (for RectCollide; the half-height of the node's body for Contain)
#withThroughSqueeze Source
withThroughSqueeze :: forall node. Boolean -> ForceConfig node -> ForceConfig nodeLet a rectangle that is pushed from both sides go through one of them
(for RectCollide). Off by default. See RectCollideConfig.
#withRegions Source
withRegions :: forall node. Array Region -> ForceConfig node -> ForceConfig nodeSet the regions (for Contain); withRegion says which node is in which
#withRegion Source
withRegion :: forall node. (node -> Maybe Int) -> ForceConfig node -> ForceConfig nodeAssign each node a region by its index in the regions array, or
Nothing to leave it free (for Contain)
#withHardLimit Source
withHardLimit :: forall node. Boolean -> ForceConfig node -> ForceConfig nodeTurn the correction after each tick on or off. For Contain it is the clamp into the region (off, the region only steers); for Directional it is the projection that makes the gap exact (off, the default there, the gap is only pushed towards).
#withGroup Source
withGroup :: forall node. (node -> Maybe Int) -> ForceConfig node -> ForceConfig nodeSet each node's group (for Cohesion)
#withinGroups Source
withinGroups :: forall node. (node -> Maybe Int) -> ForceConfig node -> ForceConfig nodeRestrict a ManyBody or RectCollide force to pairs of nodes in the same group
#betweenGroups Source
betweenGroups :: forall node. (node -> Maybe Int) -> ForceConfig node -> ForceConfig nodeRestrict a ManyBody or RectCollide force to pairs of nodes in different groups (a node in no group is in a different group from everyone)
#withGap Source
withGap :: forall node. Value (LinkEnds node) Number -> ForceConfig node -> ForceConfig nodeSet the gap each link's target must be beyond its source, per link if
dynamic (for Directional)
#withAxis Source
withAxis :: forall node. { x :: Number, y :: Number } -> ForceConfig node -> ForceConfig nodeSet the direction targets are pushed in; it need not be a unit vector (for Directional)
#resolveLinks Source
resolveLinks :: forall row linkRow. Array (SimulationNode row) -> Array { source :: NodeID, target :: NodeID | linkRow } -> Array (LinkEnds (SimulationNode row))Pair each link with the nodes at its ends. Links name nodes by id. A
link naming a node that is not there is left out; index counts the
links that are kept, which is the order an engine holds them in.
#linkStrengths Source
linkStrengths :: forall row. LinkStrength (SimulationNode row) -> Array (LinkEnds (SimulationNode row)) -> Array NumberOne strength per link. ByDegree is d3-force's default,
1 / min(links at the source, links at the target).
#recipe Source
recipe :: forall row. ForceConfig (SimulationNode row) -> ForceRecipe rowWhat a force of a setup is to the default engine: how to make it once the nodes and links are known.
- per node (
dynamic): every strength, radius, target and half-extent; - filters: a filtered-out node has strength 0 (ManyBody, PositionX/Y, Radial, Towards, Cohesion) or collides with nothing (Collide);
- per link: distance, strength, gap, and
ByDegree.
#linkProblem Source
linkProblem :: forall row. Setup (SimulationNode row) -> Array (SimulationNode row) -> Links -> Maybe StringWhat is wrong with the links, for this setup: node not found: <id>
for the first link end that is no node's id, if the setup has a force
that acts along the links (Link, Directional). Nothing if every end is
there, or if no force would look. This is the one condition under which
applySetup fails, on either engine.
#Setup Source
type Setup node = { forces :: Array (ForceConfig node), name :: String, params :: SetupParams }Complete setup: forces + simulation params
#defaultParams Source
defaultParams :: SetupParamsDefault simulation parameters
#setup Source
setup :: forall node. String -> Array (ForceConfig node) -> Setup nodeCreate a setup with default params
#setupWithParams Source
setupWithParams :: forall node. String -> Array (ForceConfig node) -> SetupParams -> Setup nodeCreate a setup with custom params
#getForces Source
getForces :: forall node. Setup node -> Array (ForceConfig node)Get forces from setup
#getParams Source
getParams :: forall node. Setup node -> SetupParamsGet params from setup
#addForce Source
addForce :: forall node. ForceConfig node -> Setup node -> Setup nodeAdd a force to the setup
#removeForce Source
removeForce :: forall node. String -> Setup node -> Setup nodeRemove a force by name
#updateForce Source
updateForce :: forall node. ForceConfig node -> Setup node -> Setup nodeUpdate a force by name (replace if exists)
#withAlphaDecay Source
withAlphaDecay :: forall node. Number -> Setup node -> Setup nodeSet alpha decay
#withAlphaTarget Source
withAlphaTarget :: forall node. Number -> Setup node -> Setup nodeSet alpha target
#withVelocityRetention Source
withVelocityRetention :: forall node. Number -> Setup node -> Setup nodeSet the share of its velocity a node keeps from one tick to the next (0.4 by default). 1 loses nothing; 0 stops every node dead each tick.
#withVelocityDecay Source
withVelocityDecay :: forall node. Number -> Setup node -> Setup nodeDeprecated: the old name of withVelocityRetention, kept so that
existing code compiles. It does exactly what it always did: the number
is the share of velocity KEPT each tick, not the share lost, which is
the opposite of what d3 means by velocityDecay.
#applySetup Source
applySetup :: forall row linkRow. Setup (SimulationNode row) -> Simulation row linkRow -> Effect UnitApply a setup to a simulation.
This is idempotent - calling with the same setup does minimal work:
- Forces in setup but not simulation: create and add
- Forces in simulation but not setup: remove
Every force is made afresh for the simulation's current nodes and links:
dynamic values, filters, groups and regions are evaluated then, once
per node or per link. Apply the setup again after changing what they
read. Each tick applies the forces in order of their names.
Throws, before changing anything, if a link names a node that is not
among the nodes and the setup has a force along the links (node not
found: <id>, as d3-force says it). tryApplySetup returns that as a
value instead.
The setup's params (alpha, alphaMin, alphaDecay, alphaTarget, velocityRetention) become the simulation's, replacing what it was created with.
Example:
-- Initial setup
applySetup mySetup sim
-- Later: update setup (just call again)
applySetup (mySetup # removeForce "charge") sim
#tryApplySetup Source
tryApplySetup :: forall row linkRow. Setup (SimulationNode row) -> Simulation row linkRow -> Effect (Either String Unit)applySetup, with the one thing that can go wrong as a value: Left
names the first link end that is no node's id (node not found: <id>),
and the simulation is left as it was.
#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
#applySetupWithData Source
applySetupWithData :: forall row linkRow. Setup (SimulationNode row) -> Array (SimulationNode row) -> Array { source :: NodeID, target :: NodeID | linkRow } -> Simulation row linkRow -> Effect { links :: GUPLinkResult linkRow, nodes :: GUPResult (SimulationNode row) }Apply setup with new nodes and links, using GUP (General Update Pattern) semantics.
This function handles three concerns:
- Force configuration (same as applySetup)
- Node GUP: diff desired nodes vs current, merge simulation state for updates
- Link GUP: diff desired links vs current
Simulation state preservation (for updated nodes):
- x, y: Current position (preserved)
- vx, vy: Current velocity (preserved)
- fx, fy: Pinned position (preserved)
- All other fields: Taken from desired nodes
Example usage:
-- Stop simulation before transition
Sim.stop sim
-- Apply new configuration and data
result <- applySetupWithData mySetup newNodes newLinks sim
-- Use result for animations
animateEnter result.nodes.entered
animateExit result.nodes.exited
-- Restart simulation
Sim.reheat sim
#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
#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 linkRowCompute link GUP: which links are entering, updating, exiting Links are keyed by (source, target) pair
#mergeSimulationState Source
mergeSimulationState :: forall row. SimulationNode row -> SimulationNode row -> SimulationNode rowMerge simulation-managed state from current node into desired node
Preserves: x, y, vx, vy, fx, fy (simulation-managed) Takes from desired: everything else (application data)
#addForceToSim Source
addForceToSim :: forall row linkRow. ForceConfig (SimulationNode row) -> Simulation row linkRow -> Effect UnitAdd a single force to simulation (without full setup). Throws if a link names a node that is not among the nodes.
#removeForceFromSim Source
removeForceFromSim :: forall row linkRow. String -> Simulation row linkRow -> Effect UnitRemove a single force from simulation by name
- Modules
- Hylograph.
Config. Force - Hylograph.
Config. Scene - Hylograph.
ForceEngine - Hylograph.
ForceEngine. Core - Hylograph.
ForceEngine. Demo - Hylograph.
ForceEngine. Events - Hylograph.
ForceEngine. Links - Hylograph.
ForceEngine. Registry - Hylograph.
ForceEngine. Render - Hylograph.
ForceEngine. Setup - Hylograph.
ForceEngine. Setup. WASM - Hylograph.
ForceEngine. Simulation - Hylograph.
ForceEngine. Types - Hylograph.
ForceEngine. WASM - Hylograph.
ForceEngine. WASMEngine - Hylograph.
Scene. Engine - Hylograph.
Scene. Handle - Hylograph.
Scene. Rules - Hylograph.
Scene. Types - Hylograph.
Simulation - Hylograph.
Simulation. Emitter - Hylograph.
Simulation. HATS - Hylograph.
Simulation. Scene - Hylograph.
Simulation. Stepped - Hylograph.
Transition. Consumers - Hylograph.
Transition. Example
A constant, or computed per link.