All 48 libraries

SugarSpring

Damped spring physics + Newtonian projectile simulation

inspired by charmbracelet/harmonica physics animation math reduced-motion

SugarSpring code coverage

sugar-spring is a pure-math animation engine. It provides damped harmonic springs for smooth motion and controlled overshoot, a Newtonian projectile integrator for arcs and particle fields, CSS-compatible easing and cubic-bezier curves, and spring chains and collections that drive many values at once. It has no terminal I/O, no ReactPHP dependency and no render path: values go in, values come out, and your frame loop decides when to paint. The spring core mirrors charmbracelet/harmonica, the Go library for the same job, and the damped-oscillator math follows Ryan Juckett's spring physics articles.

Install

composer require sugarcraft/sugar-spring

Requires PHP 8.3 or newer. The package depends on sugarcraft/sugar-core and sugarcraft/sugar-colorprofile, and both track dev-master, so the plain command resolves only when dev stability is allowed. Pin the package with composer require sugarcraft/sugar-spring:@dev, or set minimum-stability to dev with prefer-stable set to true in the consuming manifest. At runtime the library reads one thing from sugar-colorprofile: the reduced-motion probe.

Quickstart

use SugarCraft\Spring\{Spring, Projectile, Point, Vector};

$spring = new Spring(
    deltaTime:        Spring::fps(60),
    angularFrequency: 6.0,
    dampingRatio:     1.0,    // critical: fastest approach, no overshoot
);

$pos = 0.0;
$vel = 0.0;
$target = 100.0;
$frame = 0;
while (!Spring::settled($pos, $vel, $target) && $frame < 600) {   // stop on settled(), not a fixed count
    [$pos, $vel] = $spring->update($pos, $vel, $target);
    $frame++;
}

$ball = Projectile::new(
    deltaTime:    Spring::fps(60),
    position:     Point::zero(),
    velocity:     new Vector(5.0, 10.0),   // +y is up: Projectile::gravity() is (0, -9.81, 0)
    acceleration: Projectile::gravity(),
);
for ($i = 0; $i < 60; $i++) {
    $ball = $ball->update();              // update() returns a NEW Projectile: reassign it
}

The quickstart prints nothing. Every value it computes lives in $pos, $vel and $ball, and your render code reads them. The three examples shipped with the package print what the same maths looks like (see Examples).

Three damping regimes

The damping ratio dampingRatio picks the regime. The output below is php examples/spring.php, trimmed to its first rows, with all three springs driving the same target of 100 at angularFrequency = 6:

frame │ under-damped ζ=0.3     │ critical ζ=1.0         │ over-damped ζ=2.0
──────┼─────────────────────────┼─────────────────────────┼─────────────────────────
   0  │ ▏                  0.5 │ ▏                  0.5 │ ▏                  0.4
   4  │ █                 11.1 │ █                  9.0 │ █                  7.0
   8  │ ████              31.9 │ ███               22.8 │ ██                15.6
  12  │ ███████           57.9 │ █████             37.3 │ ███               24.0
  16  │ ██████████        84.2 │ ██████            50.7 │ ████              31.7

The under-damped column passes 100 and peaks near 137 before it comes back. The critical column approaches 100 without crossing it. The over-damped column is the slowest of the three at every row shown.

Concepts

A Spring is an immutable value. Its frame time (deltaTime), angular frequency and damping ratio are fixed at construction. update($pos, $vel, $target) returns the next [$pos, $vel] pair and keeps no state of its own. The caller owns the state and the clock: call update() once per frame, at the rate the spring was built for, and the motion tracks wall-clock time. The same applies to Projectile, whose update() returns a new projectile.

The frame time is baked in

Spring::fps(60) returns 1/60 of a second. A spring built with it advances one 60th of a second per update() call, so a loop that runs at 30 Hz stretches the animation to twice its length. Replays stay deterministic if you record tick counts rather than wall-clock time. For a real loop that measures frame time, rebuild the spring with the measured deltaTime each frame; coefficient setup is cheap, about a microsecond.

Done means settled, not a frame count

Spring::settled($pos, $vel, $target, $threshold) is the stop predicate. It needs the position within the threshold (default Spring::SETTLING_THRESHOLD, 1e-4) and the velocity below it. A position-only check gives false positives on under-damped springs, which cross the target at full speed and come back. A frame budget is only a safety cap: the Molasses preset alone needs 439 frames to settle at 60 fps.

Y-up coordinates

Projectile gravity points down the Y axis, and increasing Y means up the screen. Projectile::gravity() returns (0, -9.81, 0) and Projectile::terminalGravity() returns (0, -53, 0). Terminal renderers usually grow downward, so Projectile::gravityYDown() and terminalGravityYDown() keep the same magnitudes with the sign flipped.

Tasks

Animate a value one frame at a time

Step the spring once per paint and convert the position to a cell only when you draw:

use SugarCraft\Spring\Spring;

$spring = new Spring(Spring::fps(60), 6.0, 1.0);
$pos = 0.0;
$vel = 0.0;

// One update and one paint per frame. Never run a settle loop inside a frame.
[$pos, $vel] = $spring->update($pos, $vel, 100.0);
$cell = (int) round($pos);   // the integer cell to draw this frame

If $cell is unchanged from the previous frame, skip the repaint. Pass a cell-sized threshold such as 0.5 to settled() when the consumer renders at cell resolution, because a spring usually stops changing the frame well before it stops settling at 1e-4.

Pick a feel with a preset

use SugarCraft\Spring\{Spring, SpringPreset};

$spring = Spring::fromPreset(SpringPreset::Wobbly);                       // 60 fps by default
$slow   = Spring::fromPreset(SpringPreset::Molasses, Spring::fps(30));    // explicit frame time

The five presets and their measured settle times are in Configuration.

Stagger stages with a spring chain

A SpringChain runs one stage at a time. Each stage is a [Spring, position, velocity, target] tuple, and the next stage starts when the active one settles:

use SugarCraft\Spring\{Spring, SpringChain, SpringPreset};

$chain = (new SpringChain([]))
    ->withStage(Spring::fromPreset(SpringPreset::Gentle), 0.0, 0.0, 50.0)
    ->withStage(Spring::fromPreset(SpringPreset::Wobbly), 0.0, 0.0, 100.0)
    ->withStage(Spring::fromPreset(SpringPreset::Stiff),  0.0, 0.0, 75.0);

while (!$chain->isComplete()) {
    $chain = $chain->tick();              // reassign: tick() returns the advanced chain
    $positions = $chain->currentPositions();
}

Build the full stage list before the first tick(). withStage() restarts the new chain at stage 0, so calling it mid-run throws the progress away.

Drive many named values with a spring collection

use SugarCraft\Spring\{Spring, SpringCollection, SpringPreset};

$group = (new SpringCollection())
    ->withSpring('menu',  Spring::fromPreset(SpringPreset::Stiff),    0.0, 0.0, 40.0)
    ->withSpring('panel', Spring::fromPreset(SpringPreset::Molasses), 0.0, 0.0, 90.0);

$frame = 0;
while (!$group->settled() && $frame < 600) {
    $group = $group->tick();              // a new collection; every member advances
    $frame++;
}

echo sprintf("menu=%.2f panel=%.2f\n", $group->position('menu'), $group->position('panel'));

Read values with position($id), target($id), velocity($id) and all(). Ids that are not in the collection throw an OutOfBoundsException that names the id.

Re-aim a projectile between frames

use SugarCraft\Spring\{Point, Projectile, Spring, Vector};

$p = Projectile::new(Spring::fps(60), Point::zero(), new Vector(5.0, 10.0), Projectile::gravity());
$p = $p->withVelocity(new Vector(-2.0, 4.0));    // a new Projectile with one field swapped
$p = $p->update();                              // reassign: update() never mutates the receiver

Use a CSS-style timing curve

use SugarCraft\Spring\Easing\{CubicBezier, Easing};

$curve  = CubicBezier::easeOutCubic();        // control points 0.22, 0.61, 0.36, 1.00
$custom = new CubicBezier(0.25, 0.10, 0.25, 1.00);
$named  = Easing::CubicOut;                   // the same family as an enum case

$a = $curve->ease(0.5);
$b = $custom->ease(0.5);
$c = $named->ease(0.5);

Honour reduced motion in a non-spring curve

Projectile, Easing and CubicBezier are pure functions of time with no target to snap to, so they ignore the reduced-motion signal. Gate them in the application by jumping to the end of the motion when the user asks for less of it:

use SugarCraft\ColorProfile\Probe;
use SugarCraft\Spring\Easing\Easing;

$frame = 12;                                            // 12th frame of a 60-frame motion
$t = Probe::reducedMotion() ? 1.0 : $frame / 60.0;      // t = 1.0 is "already there"
$progress = Easing::CubicOut->ease($t);

API reference

The value classes are final and immutable. Methods that change state return a new instance, and the table names the return type where it matters. Bare accessors have no get prefix.

Spring and SpringConfig

ClassMemberDescription
Spring__construct(deltaTime, angularFrequency, dampingRatio, reducedMotionOverride = null)Refuses non-finite input, deltaTime ≤ 0, angularFrequency < 1e-9, dampingRatio ≤ 0 and coefficient overflow
Springnew(...)House factory with the same arguments and guarantees as the constructor
Springupdate(pos, vel, target): arrayOne step; returns [position, velocity] with both named and positional keys. Snaps to [target, 0.0] under reduced motion
Springsettled(pos, vel, target, threshold = 1e-4): boolStatic. Position and velocity both within the threshold
Springfps(n): floatStatic. Returns 1 / n; refuses non-finite, non-positive and overflowing rates
SpringfromPreset(preset, deltaTime = null, reducedMotionOverride = null)Static. Builds a spring from a SpringPreset at 60 fps unless a frame time is given
SpringdeltaTime(), angularFrequency(), dampingRatio(), reducedMotionOverride()Accessors for the constructor inputs
SpringresetReducedMotionProbe(): voidStatic. Forgets the memoised environment read so the next update() re-probes it
SpringConfig__construct(tension, friction, mass) and new(...)Physical units. Public readonly $angularFrequency and $dampingRatio are derived at construction
SpringConfigspring(deltaTime = 1/60, reducedMotionOverride = null): SpringBuilds the matching Spring
SpringPresetGentle, Wobbly, Stiff, Slow, MolassesEnum. resolve(): SpringConfig returns the preset's physical triple

SpringChain and SpringCollection

ClassMemberDescription
SpringChain__construct(stages, activeIndex = 0) and new(stages)Stages are [Spring, position, velocity, target]. Malformed stages and out-of-range indexes are refused
SpringChainwithStage(spring, position, velocity, target): selfBuild time only. Returns a chain restarted at stage 0
SpringChaintick(): selfAdvances the active stage. Reassign the result, or the run never moves on
SpringChaincurrentPositions(): list<float>, isComplete(): bool, activeStage(): intRead the state of the chain as of its last tick
SpringChainSETTLING_THRESHOLD = 5e-4The hand-off threshold. Looser than Spring::SETTLING_THRESHOLD on purpose
SpringCollection__construct(springs, positions, velocities, targets)Keyed by id. The positions, velocities and targets maps must cover the same ids as the springs
SpringCollectionwithSpring(id, spring, position, velocity, target), without(id), withTarget(id, target)Copy-on-write. Each returns a new collection
SpringCollectiontick(): selfAdvances every member one frame and returns a new collection
SpringCollectionposition(id), velocity(id), target(id), all(), allVelocities(), has(id)Readers. Unknown ids throw OutOfBoundsException
SpringCollectionsettled(threshold = 1e-4): boolTrue when every member has settled

Projectile, Point and Vector

ClassMemberDescription
Projectilenew(deltaTime, position, velocity, acceleration)Explicit Euler integrator. The construction door refuses non-finite values
Projectileupdate(): selfReturns a new projectile one step ahead. The receiver is not changed
Projectileposition(), velocity(), acceleration()The same values as the public readonly properties
ProjectilewithPosition(), withVelocity(), withAcceleration(), withDeltaTime()Each returns a new projectile with one field swapped and the other three kept
Projectilegravity(), terminalGravity(), gravityYDown(), terminalGravityYDown()Static. Shared immutable Vector presets
ProjectileGRAVITY = 9.81, TERMINAL_GRAVITY = 53.0Magnitudes behind the presets
Pointnew(x, y, z = 0.0), zero(), add(Vector), delta(Point): Vector, distance(Point)Immutable 3D position. Components must be finite
PointfromArray(list), jsonSerialize()Wire format is the positional [x, y, z] list
Vectornew(x, y, z = 0.0), zero(), add(), sub(), scale(), dot(), cross(), lerp()Immutable 3D vector. Components must be finite
Vectorlength(), lengthSquared(), normalize(): selfnormalize() throws RuntimeException for a zero or overflowed length, not InvalidArgumentException

Easing and CubicBezier

ClassMemberDescription
EasingEnum of 16 cases: Linear, QuadraticIn/Out/InOut, CubicIn/Out/InOut, ElasticIn/Out/InOut, BounceIn/Out/InOut, BackIn/Out/InOutImplements EasingFunction. ease(t): float takes a normalised time t; Elastic and Back cases may overshoot
CubicBezier__construct(x1, y1, x2, y2) and new(...)CSS cubic-bezier() control points. The x values must lie in [0, 1]; y may overshoot
CubicBezierease(t): floatEvaluates the curve. Refuses non-finite t
CubicBezier26 static presets such as cssEase(), easeIn(), easeOutCubic(), easeInOutExpo()Memoised. The five CSS keywords plus 21 Penner-style families (Sine, Quad, Cubic, Quart, Quint, Expo, Circ)

Only methods declared in sugar-spring/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Spring

Lang final class

Per-library translation facade for sugar-spring.

Point final class

3D point. Same shape as Vector; kept as a distinct type for the same reason harmonica does — semantically a position vs. a delta.

MethodSummary
__construct(public readonly float $x, public readonly float $y, public readonly float $z = 0.0)
static zero(): self
static new(float $x, float $y, float $z = 0.0): selfFactory alias of the constructor — the house ::new() entry shape (finding 052); the same door as new Point(...).
add(Vector $v): selfAdd a Vector delta to this point, returning a new Point.
delta(self $to): VectorThe motion primitive: the Vector from this point to $to ($to − $this — the displacement a spring or projectile must traverse to get HERE there). Feeds Vector-returning callers (normalize for a direction, length for a budget) without hand-writing the subtraction. Coordinates near 1e308 overflow the difference to INF, which the Vector door refuses outright — distance() returns INF for that pair instead (it never builds a Vector); the asymmetry is by construction, not drift.
distance(self $other): floatEuclidean distance to another point. Returns INF when the squared deltas sum past PHP_FLOAT_MAX (extreme coordinates ~1e154 and up).
__toString(): string
static fromArray(array $wire): selfRebuild from the wire format jsonSerialize() emits: a positional [x, y, z] list (Point carries z like Vector — the serializer always emits three entries). **The index order is contractual and frozen**: this method and the serializer are two halves of one wire format. int entries (json_decode of 1 yields an int) are widened here; wrong arity or type is refused before the constructor sees a partial tuple, and finiteness stays the constructor's own door.
jsonSerialize(): arrayWire format: positional [x, y, z]. The index order is contractual — fromArray() decodes this exact shape and a re-ordered or keyed payload is a breaking change, not a style edit.

Projectile final class

Newtonian-physics projectile. Mirrors charmbracelet/harmonica.NewProjectile.

MethodSummary
__construct(public readonly float $deltaTime, public readonly Point $position, public readonly Vector $velocity, public readonly Vector $acceleration)
static new(float $deltaTime, Point $position, Vector $velocity, Vector $acceleration): self
update(): selfAdvance the simulation by one step. Returns a new Projectile — the original is untouched. Position += velocity·dt; velocity += acceleration·dt.
withPosition(Point $position): selfNew projectile at $position, same velocity/acceleration/frame time.
withVelocity(Vector $velocity): selfNew projectile with $velocity, same position/acceleration/frame time.
withAcceleration(Vector $acceleration): selfNew projectile with $acceleration, same position/velocity/frame time.
withDeltaTime(float $deltaTime): selfNew projectile stepping at $deltaTime, same state. 0.0 is a LEGAL value here (the accepted-freeze idiom, finding 049) and must not be swallowed by a naive null-coalescing rebuild — pinned.
position(): Point
velocity(): Vector
acceleration(): Vector
static gravity(): VectorGravity vector — Y-up, matching upstream harmonica Gravity = Vector{0, -9.81, 0}. Use this when porting examples from the harmonica docs verbatim. Returns a shared immutable instance (see the memo above).
static terminalGravity(): VectorTerminal-velocity gravity — Y-up, matching upstream harmonica TerminalGravity = Vector{0, -53, 0}. Shared immutable instance.
static gravityYDown(): VectorLegacy Y-down gravity. Earlier versions of SugarSpring used (0, +9.81, 0) (Y-down) — kept here so existing PHP code that relied on the old convention can opt back in via a single name change without flipping every Y-coord in the model. Shared immutable instance.
static terminalGravityYDown(): VectorLegacy Y-down terminal-velocity gravity. See gravityYDown(). Shared immutable instance.

Spring final class

Damped harmonic oscillator (Ryan Juckett's "Damped Springs"), with under-/critically-/over-damped branches chosen by the damping ratio — readable back off any live spring via self::dampingRatio().

MethodSummary
__construct(float $deltaTime, float $angularFrequency, float $dampingRatio, ?bool $reducedMotionOverride = null)
static new(float $deltaTime, float $angularFrequency, float $dampingRatio, ?bool $reducedMotionOverride = null): selfFactory alias of the constructor — the house ::new() entry shape, one vocabulary across the library (finding 052). Spring::new(...) and new Spring(...) are the same door, not two behaviours.
update(float $pos, float $vel, float $target): arrayAdvance one step toward $target, returning the new position and velocity.
deltaTime(): floatTuning triple: seconds elapsed per integration step.
angularFrequency(): floatTuning triple: rad/sec (NOT Hz) — see the constructor note.
dampingRatio(): floatTuning triple: <1 oscillating, =1 critical, >1 over-damped.
reducedMotionOverride(): ?boolThe pinned reduced-motion override, or null when it defers to the environment.
static resetReducedMotionProbe(): voidTest seam: forget the memoized reduced-motion verdict so the next probe re-reads the environment. Production callers should never need this — the point of the memo is that a process's a11y setting is read once. Environments that DO hot-swap REDUCE_MOTION mid-run (long-lived daemons re-reading config) are the documented reason this seam is public.
static settled(float $pos, float $vel, float $target, float $threshold = self::SETTLING_THRESHOLD): boolWhether a spring resting at ($pos, $vel) has settled at $target.
static fps(float $n): floatFrame-time (seconds) for a given frame rate. Spring::fps(60) → 1/60.
static fromPreset(SpringPreset $preset, ?float $deltaTime = null, ?bool $reducedMotionOverride = null): SpringConstruct a spring from a named preset at 60 fps.

SpringChain final class

Sequences multiple springs so that one spring's settle triggers the next.

MethodSummary
__construct(array $stages, int $activeIndex = 0)
static new(array $stages): selfBuild a chain from a spring and initial conditions for each stage.
withStage(Spring $spring, float $position, float $velocity, float $target): selfAdd a stage to the end of the chain (fluent).
tick(): selfAdvance the chain by one step, returning the NEW chain.
currentPositions(): arrayGet all current positions of all stages.
isComplete(): boolCheck if the chain has completed all stages.
activeStage(): intGet the index of the currently active stage.

SpringCollection final class

Manages multiple named spring instances.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(array $springs = [], array $positions = [], array $velocities = [], array $targets = [])
withSpring(string $id, Spring $spring, float $position = 0.0, float $velocity = 0.0, float $target = 0.0): selfReturn a NEW collection with the given spring added (immutable).
without(string $id): selfReturn a NEW collection with the named spring removed (immutable).
withTarget(string $id, float $target): selfReturn a NEW collection with the target for one spring changed (immutable).
tick(): selfAdvance every UNSETTLED spring by one step; settled members keep their floats untouched (finding 006 — cost follows motion, not collection size). Returns a NEW SpringCollection when anything advanced, leaving the original instance unchanged; a fully-settled collection returns $this identity.
position(string $id): floatThe current position of a spring by id — the house bare accessor.
velocity(string $id): floatGet the current velocity of a spring by id.
allVelocities(): arrayGet all current velocities, keyed by spring id.
settled(float $threshold = Spring::SETTLING_THRESHOLD): boolWhether EVERY spring in the collection has settled at its target.
has(string $id): boolCheck if a spring exists in the collection.
all(): arrayGet all current positions.
target(string $id): floatGet the target for a specific spring.

SpringConfig final readonly class

The tension / friction / mass triple behind a Spring: physical parameters the class turns into the angular frequency and damping ratio the oscillator integrates with.

MethodSummary
static new(float $tension, float $friction, float $mass): selfFactory alias of the constructor — the house ::new() entry shape (finding 052); the same door as new SpringConfig(...).
__construct(public float $tension, public float $friction, public float $mass)
spring(float $deltaTime = 1.0 / 60.0, ?bool $reducedMotionOverride = null): SpringBuild a spring from this config's derived values.

SpringPreset enum

Predefined spring parameter sets for common animation moods.

Cases: Gentle · Wobbly · Stiff · Slow · Molasses

PHP also provides cases().

MethodSummary
resolve(): SpringConfigResolve this preset to a fully constructed SpringConfig. The returned instance is SHARED per preset (immutable by type).

Vector final class

3D vector for Projectile. Immutable.

MethodSummary
__construct(public readonly float $x, public readonly float $y, public readonly float $z = 0.0)
static zero(): self
static new(float $x, float $y, float $z = 0.0): selfFactory alias of the constructor — the house ::new() entry shape (finding 052); the same door as new Vector(...).
add(self $other): self
sub(self $other): self
scale(float $s): selfScale all three components by $s.
length(): floatEuclidean length in 3D. Returns INF when the squared components sum past PHP_FLOAT_MAX (finite components ~1e154 and up).
dot(self $other): floatDot product.
cross(self $other): selfCross product. Returns a new perpendicular Vector.
lengthSquared(): floatSquared Euclidean length — avoids sqrt() for comparisons. Returns INF on overflow exactly like length() (components ~1e154 and up).
normalize(): selfNormalized (unit) vector.
lerp(self $other, float $t): selfLinear interpolation between this vector and $other.
__toString(): string
static fromArray(array $wire): selfRebuild from the wire format jsonSerialize() emits: a positional [x, y, z] list. **The index order is contractual and frozen** — this method and the serializer are two halves of one wire format, so no component may ever move or gain a name. int entries (json_decode of 1 yields an int) are widened here; everything else about the members — type, arity — is refused before the constructor ever sees a partial tuple, and finiteness stays the constructor's own door (one guard, no duplicated policy).
jsonSerialize(): arrayWire format: positional [x, y, z]. The index order is contractual — fromArray() decodes this exact shape and a re-ordered or keyed payload is a breaking change to every serialized vector, not a style edit.

SugarCraft\Spring\Easing

CubicBezier final class

Cubic Bezier easing functions — matches the CSS cubic-bezier() spec.

MethodSummary
__construct(float $x1, float $y1, float $x2, float $y2)
static new(float $x1, float $y1, float $x2, float $y2): selfFactory alias of the constructor — the house ::new() entry shape (finding 052), SHIPPED rather than exempted on purpose: this class already serves static calls with named presets, and the uniform door costs nothing next to teaching five classes one vocabulary. Custom (off-table) curves take this door; the 26 named ones take their presets, which stay the memoized shared instances.
static cssEase(): selfThe CSS ease transition-timing-function keyword. Named cssEase() because the seam sampler ease() owns the bare spelling — PHP forbids one name as both static preset and instance sampler. The legacy static CubicBezier::ease() cannot forward through __callStatic() (the engine resolves it to the instance method and raises an Error) and fails loudly instead; migrate to cssEase().
static easeIn(): self
static easeOut(): self
static easeInOut(): self
static linear(): self
static __callStatic(string $name, array $arguments): selfBC door for the CSS-keyword preset, honestly stated: PHP resolves a static call to the instance sampler ease() and raises an Error WITHOUT consulting __callStatic, so no deprecation forwarder can exist for CubicBezier::ease(). The legacy spelling fails LOUDLY until 2.0.0; cssEase() is the preset. This hook guards the other static misses only: a typo must fail with a named refusal here, not quietly become some preset.
static easeInSine(): self
static easeOutSine(): self
static easeInOutSine(): self
static easeInQuad(): self
static easeOutQuad(): self
static easeInOutQuad(): self
static easeInCubic(): self
static easeOutCubic(): self
static easeInOutCubic(): self
static easeInQuart(): self
static easeOutQuart(): self
static easeInOutQuart(): self
static easeInQuint(): self
static easeOutQuint(): self
static easeInOutQuint(): selfPre-2022 easings.net approximation: cubic-bezier(0.86, 0, 0.07, 1). (The site's 2022 redesign table lists (0.83, 0, 0.17, 1) instead; this preset family consistently ships the original table, see the class docblock.)
static easeInExpo(): self
static easeOutExpo(): self
static easeInOutExpo(): self
static easeInCirc(): self
static easeOutCirc(): self
static easeInOutCirc(): selfPre-2022 easings.net approximation: cubic-bezier(0.785, 0.135, 0.15, 0.86).
ease(float $t): floatEase normalized time $t ∈ [0, 1] through this curve — the seam sampler of EasingFunction.

Easing enum

Standard easing functions for animation.

Cases: Linear · QuadraticIn · QuadraticOut · QuadraticInOut · CubicIn · CubicOut · CubicInOut · ElasticIn · ElasticOut · ElasticInOut · BounceIn · BounceOut · BounceInOut · BackIn · BackOut · BackInOut

PHP also provides cases().

MethodSummary
ease(float $t): floatApply the easing function to a normalized time value.

EasingFunction interface

Interface for custom easing functions.

MethodSummary
ease(float $t): floatApply the easing function to a normalized time value.

Configuration

Spring constructor inputs

OptionTypeDefaultEffect
deltaTimefloatnone (required)Seconds per update() call. Must be finite and > 0. Use Spring::fps(60) for a 60 Hz loop
angularFrequencyfloatnone (required)Speed in radians per second. Must be finite and at least 1e-9. Larger values settle faster
dampingRatiofloatnone (required)The regime. Must be > 0. Below 1 oscillates, exactly 1 is critical, above 1 is over-damped
reducedMotionOverride?boolnullnull defers to the environment. false animates even when reduced motion is requested. true snaps to target even when it is not

Spring presets

Spring::fromPreset() builds a spring at 60 fps from one of five hand-tuned presets. The presets are not literal UIKit values. They were tuned against the react-spring-era tables, and every one is under-damped, so each overshoots a little. The settle times below were measured for a move from 0 to 100 at the default 1e-4 threshold:

PresetTensionFrictionMassζOvershootSettle at 60 fps
Gentle1001010.50about 16%174 frames (about 2.9 s)
Wobbly1801210.45about 21%141 frames (about 2.4 s)
Stiff5002010.45about 21%94 frames (about 1.6 s)
Slow50610.42about 23%292 frames (about 4.9 s)
Molasses30410.37about 29%439 frames (about 7.3 s)

No critically damped preset ships. Build one with dampingRatio: 1.0, or with new SpringConfig(...) and a friction of 2 * sqrt(tension * mass).

SpringConfig physical units

SpringConfig takes tension, friction and mass, which must all be finite and greater than zero, and derives the two numbers Spring consumes:

angularFrequency = sqrt(tension / mass)
dampingRatio     = friction / (2 * sqrt(tension * mass))
use SugarCraft\Spring\SpringConfig;

$config  = new SpringConfig(tension: 180.0, friction: 12.0, mass: 1.0);
$spring  = $config->spring();                                   // 1/60 s frame time
$pinned  = $config->spring(reducedMotionOverride: true);        // always snaps, env ignored
echo $config->angularFrequency;                                 // 13.416... (public readonly)

Extreme but finite triples are refused when the derived values are not finite, not positive or numerically degenerate. Past a damping ratio of about 226.5, the two over-damped roots collapse to one number and the spring would freeze.

Reduced-motion environment

VariableValueEffect
REDUCE_MOTIONunset, 0, false, no or off (any case)Off. Springs animate normally
REDUCE_MOTIONany other non-empty value, 1 includedOn. Springs snap to target
PREFERS_REDUCED_MOTIONsame rules as aboveConsulted after REDUCE_MOTION. Either variable reading on is enough, so an off value in one never cancels an on value in the other

The environment is read once per process, on the first update() that needs it, and the answer is remembered. Changing the variable later in the same process does not change behaviour until Spring::resetReducedMotionProbe() is called. A per-spring reducedMotionOverride is checked on every call and always wins over the memo. The lookup goes through SugarCraft\ColorProfile\Probe::reducedMotion(), and no terminal query or accessibility daemon is consulted.

Examples

The three examples live in examples/. None takes arguments, and each runs from the package root after composer install.

examples/spring.php

Drives the same target through three damping ratios and prints the rows side by side (see Quickstart for the output). Under REDUCE_MOTION every update() snaps to target, so the example prints flat lines and says so once.

php examples/spring.php

examples/projectile.php

Traces one two-dimensional arc over its first 90 frames (1.5 s at 60 fps). The initial velocity points up and to the right, and gravity bends it over. The example plots those samples as an ASCII curve, and the plot stops before the apex, so it shows only the rising half of the arc. Projectile ignores the reduced-motion signal by design, and the example prints one line when the variable is set.

php examples/projectile.php

examples/particle.php

Spawns 80 projectiles from the origin, each with a randomised velocity and a small position offset, runs 60 frames under Y-up gravity, and plots every frame position of each particle into one grid. The random generator is seeded with mt_srand(42), so the output is the same on every run.

php examples/particle.php

Testing

cd sugar-spring && composer install && vendor/bin/phpunit

The suite lives in tests/. GoldenRenderTest compares the spring and projectile trajectories with the files in tests/fixtures/. Run it with UPDATE_GOLDENS=1 vendor/bin/phpunit to record new fixtures after an intentional change. ReducedMotionTest and ReducedMotionOverrideTest cover the environment probe and the per-spring override. LocaleParityTest keeps all 16 language files in step with lang/en.php. AccessorDeprecationTest checks the removed-aliases table in the README against the source.

Troubleshooting

The constructor throws "dampingRatio must be > 0"

A damping ratio of zero is an oscillator that never settles, and a negative one diverges. Use a value above zero. 1.0 is critically damped and the fastest approach without overshoot.

The animation runs too fast or too slow

The frame time is fixed when the spring is built. If the loop calls update() at 30 Hz but the spring was built with Spring::fps(60), the motion takes twice as long. Build the spring with the rate you really call it at, or rebuild it each frame with the measured deltaTime (clamped, so a stall cannot teleport the value).

Values jump straight to the target

REDUCE_MOTION or PREFERS_REDUCED_MOTION is set to a value other than 0, false, no or off. This is deliberate. Pin the spring with reducedMotionOverride: false if the motion carries information the end state does not. Call Spring::resetReducedMotionProbe() if the variable changed after the first probe in the same process.

The chain or the projectile never moves

SpringChain::tick(), SpringCollection::tick() and Projectile::update() return a new value. Assign it back ($chain = $chain->tick();). Discarding the return value leaves the receiver untouched, and the loop replays the same frame forever.

A loop never settles on a small threshold

settled() needs both the position and the velocity within the threshold, and the default 1e-4 is finer than one terminal cell. Pass 0.5 when you render at cell resolution, and keep a frame cap such as $frame < 600 as an escape hatch.

normalize() throws a RuntimeException

Vector::normalize() has no honest answer for a zero-length or overflowed vector, so it throws RuntimeException, not InvalidArgumentException. Check length() first, or catch RuntimeException around the call.

Upstream mapping

SugarCraftcharmbracelet/harmonicaNotes
Spring (new, update)harmonica.NewSpring, Spring.UpdateMirrors the spring core. The Ryan Juckett damped-oscillator algorithm is shared upstream
Projectileharmonica.NewProjectile, Projectile.UpdateExplicit Euler integration. Returns a new value instead of mutating
Projectile::GRAVITY, gravity()harmonica.GravityStandard gravity, Y-up
Projectile::TERMINAL_GRAVITY, terminalGravity()harmonica.TerminalGravityApproximate skydiver terminal velocity, Y-up
Pointharmonica.PointA position, kept apart from a delta on purpose, as upstream does
Vectorharmonica.VectorThe same 3D value type
SpringConfig, SpringPreset, SpringChain, SpringCollection, Easing, CubicBezier, reduced motionnoneSugarCraft additions. Easing follows the CSS cubic-bezier() algorithm and the easings.net control points

Mapping lives in the class doc comments, which cite Mirrors charmbracelet/harmonica.<Method> where the port is direct. The full upstream-to-port table is in docs/MATCHUPS.md.

Architecture

Pure values, no I/O

sugar-spring has no event loop, no ReactPHP, no ext-pcntl and no output path. Each step is a function of its inputs. update() takes (pos, vel, target) and returns a new pair, so a spring can be shared between several frame loops without any coordination.

Immutable state with checked doors

Constructors refuse bad input, and the with*() builders go through the same checks. A value that overflows to infinity mid-simulation is refused by the constructor that would have stored it, so a bad state never reaches the caller.

The reduced-motion memo

The environment is read at most once per process, and the result is memoised in a static. The per-spring override is evaluated on every call. The probe lives in sugar-colorprofile, and it is the only sugar-colorprofile call the spring path makes.

Messages in every locale

Exception messages go through SugarCraft\Spring\Lang::t(), which sits on the shared SugarCraft\Core\I18n machinery. Lookup runs exact locale, then base locale, then en, then the raw key. Set the locale once with SugarCraft\Core\I18n\T::setLocale('de').

Changelog and versioning

The package was published as sugarcraft/honey-bounce until its rename in 2026-10, and its namespace changed from SugarCraft\Bounce\ to SugarCraft\Spring\. Removed APIs are listed in the README table titled Removed aliases (2.0.0), with the canonical replacement for each. That table is pinned to the source by AccessorDeprecationTest, so it cannot drift silently.

  • sugarcraft/sugar-colorprofile: the Probe that answers the reduced-motion question.
  • sugarcraft/sugar-overlay: the Fade, Scale and Slide overlay animations consume the easing seam, including the CubicBezier presets.
  • sugarcraft/sugar-widgets: AnimatedProgress caches one Spring for its lifetime and steps it on each tick.
  • sugarcraft/candy-flappy: Bird integrates a Projectile for its flap-and-fall arc.

Source & demos

Try the quickstart →

Demos.

VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.

Looping recording of a damped spring easing smoothly to its target value

Spring

Damped harmonic oscillator — settles smoothly to its target.
Looping recording of a projectile tracing the rising half of a gravity arc

Projectile

Newtonian projectile arc under gravity.
Looping recording of a projectile-driven particle field rising and slowing under gravity

Particle

Projectile-driven particle field with gravity.