Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(curve): one curve, sampled by everything that has one

esengine85fa6ef85232
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca124abf4..0716da687 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,37 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Changed
+
+- **One curve, sampled by everything that has one.** A timeline channel carried keys
+ with tangents and six interpolations, drawn by an editor that understood them; a
+ particle's size-over-life carried `{t, v}` pairs joined by straight lines; and the
+ Inspector's curve control carried a third copy of the second. Three shapes for "a
+ value that changes over a span", and the seam between them was invisible because each
+ half worked — a particle curve simply could not be told to ease, and nothing said so.
+
+ `math/keyframes` now owns the shape and the sampler. `evaluateChannel` is one call
+ into it, `bakeCurve` is another, and `TimelineTypes` re-exports rather than restates.
+ A particle curve gains tangents and all six interpolations by arriving; where `time`
+ runs stays the caller's — seconds for a timeline, 0..1 of a life for a particle.
+
+ The editor's curve control now DRAWS through the same sampler instead of connecting
+ its points with straight lines. An eased or hermite segment used to look straight
+ while bending in the game; what an author sees is now what the sim bakes, by
+ construction rather than by keeping two renderings in step. Its selected key gained
+ an interpolation picker, which is the field the old shape had nowhere to put.
+
+ BREAKING (`@beta`): `ParticleEmitterData.sizeCurve` keys are
+ `{ time, value, inTangent, outTangent, interpolation? }` rather than `{ t, v }`.
+ Nothing exported the old type, so a curve could only be written as a literal; the two
+ fixture scenes that held one are migrated. A curve whose keys are not finite is now
+ REFUSED with a warning rather than baked — the old shape read as `NaN`, and a particle
+ sized `NaN` does not draw, so the emitter vanished with nothing said. Falling back to
+ start/end size is wrong, but it is visible.
+
+ `GradientStop` is deliberately NOT folded in: a colour stop is not a scalar key, and
+ one shape for both would be a name over two things.
+
### Added
- **A sprite can be cut by another sprite's shape.** 2D needed a hole and had no way to
diff --git a/desktop b/desktop
index 3b463c66c..6eb4424eb 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 3b463c66c6366db52eaa6b5c0f093e52c69a87a8
+Subproject commit 6eb4424ebed6c6a29314c18caa64a3dbf66b3519
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 03f67f577..7227795bb 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 114,
"beta": 101,
- "experimental": 1839,
+ "experimental": 1842,
"deprecated": 3
},
- "total": 2054,
+ "total": 2057,
"subsystems": [
{
"id": "ecs",
diff --git a/fixtures/scenes/particle-sizecurve.esscene b/fixtures/scenes/particle-sizecurve.esscene
index 507fe9386..a45e59756 100644
--- a/fixtures/scenes/particle-sizecurve.esscene
+++ b/fixtures/scenes/particle-sizecurve.esscene
@@ -47,8 +47,8 @@
{ "t": 1, "color": { "r": 0, "g": 1, "b": 0, "a": 1 } }
] },
"sizeCurve": { "keys": [
- { "t": 0, "v": 0.4 },
- { "t": 1, "v": 0.4 }
+ { "time": 0, "value": 0.4, "inTangent": 0, "outTangent": 0, "interpolation": "linear" },
+ { "time": 1, "value": 0.4, "inTangent": 0, "outTangent": 0, "interpolation": "linear" }
] }
}}
],
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index b4d57ac33..b13dc583c 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 94 beta · 1678 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1681 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2460,6 +2460,11 @@ Front = 2
None = 0
```
+## Curve — interface @experimental
+```
+keys: Keyframe[]
+```
+
## CustomEvent — interface @experimental
```
name: string
@@ -12243,6 +12248,11 @@ LifecyclePlugin
(aim: Vec3): Quat
```
+## linearKey — function @experimental
+```
+(time: number, value: number): Keyframe
+```
+
## loadComponent — function @experimental
```
(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void
@@ -13118,6 +13128,11 @@ ReplicationPlugin
SafeAreaPlugin
```
+## sampleKeyframes — function @experimental
+```
+(keys: readonly Keyframe[], at: number): number
+```
+
## sampleRootPlacement — function @experimental
```
(asset: TimelineAsset, time: number, out: RootPlacement): boolean
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 5ea5428ad..96cbe1f05 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 99 beta · 1697 experimental · 3 deprecated
+Symbols: 114 public · 99 beta · 1700 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2468,6 +2468,11 @@ Front = 2
None = 0
```
+## Curve — interface @experimental
+```
+keys: Keyframe[]
+```
+
## CustomEvent — interface @experimental
```
name: string
@@ -12486,6 +12491,11 @@ LifecyclePlugin
(aim: Vec3): Quat
```
+## linearKey — function @experimental
+```
+(time: number, value: number): Keyframe
+```
+
## loadComponent — function @experimental
```
(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void
@@ -13361,6 +13371,11 @@ ReplicationPlugin
SafeAreaPlugin
```
+## sampleKeyframes — function @experimental
+```
+(keys: readonly Keyframe[], at: number): number
+```
+
## sampleRootPlacement — function @experimental
```
(asset: TimelineAsset, time: number, out: RootPlacement): boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index fc8969e56..038fd0524 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 96 beta · 1677 experimental · 3 deprecated
+Symbols: 114 public · 96 beta · 1680 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2455,6 +2455,11 @@ Front = 2
None = 0
```
+## Curve — interface @experimental
+```
+keys: Keyframe[]
+```
+
## CustomEvent — interface @experimental
```
name: string
@@ -12238,6 +12243,11 @@ LifecyclePlugin
(aim: Vec3): Quat
```
+## linearKey — function @experimental
+```
+(time: number, value: number): Keyframe
+```
+
## loadComponent — function @experimental
```
(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void
@@ -13123,6 +13133,11 @@ ReplicationPlugin
SafeAreaPlugin
```
+## sampleKeyframes — function @experimental
+```
+(keys: readonly Keyframe[], at: number): number
+```
+
## sampleRootPlacement — function @experimental
```
(asset: TimelineAsset, time: number, out: RootPlacement): boolean
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 562f7af56..010529106 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 94 beta · 1699 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1702 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2455,6 +2455,11 @@ Front = 2
None = 0
```
+## Curve — interface @experimental
+```
+keys: Keyframe[]
+```
+
## CustomEvent — interface @experimental
```
name: string
@@ -12505,6 +12510,11 @@ LifecyclePlugin
(aim: Vec3): Quat
```
+## linearKey — function @experimental
+```
+(time: number, value: number): Keyframe
+```
+
## loadComponent — function @experimental
```
(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void
@@ -13380,6 +13390,11 @@ ReplicationPlugin
SafeAreaPlugin
```
+## sampleKeyframes — function @experimental
+```
+(keys: readonly Keyframe[], at: number): number
+```
+
## sampleRootPlacement — function @experimental
```
(asset: TimelineAsset, time: number, out: RootPlacement): boolean
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index ce6e57b44..387abda20 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 94 beta · 1689 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1692 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2455,6 +2455,11 @@ Front = 2
None = 0
```
+## Curve — interface @experimental
+```
+keys: Keyframe[]
+```
+
## CustomEvent — interface @experimental
```
name: string
@@ -12271,6 +12276,11 @@ LifecyclePlugin
(aim: Vec3): Quat
```
+## linearKey — function @experimental
+```
+(time: number, value: number): Keyframe
+```
+
## loadComponent — function @experimental
```
(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void
@@ -13146,6 +13156,11 @@ ReplicationPlugin
SafeAreaPlugin
```
+## sampleKeyframes — function @experimental
+```
+(keys: readonly Keyframe[], at: number): number
+```
+
## sampleRootPlacement — function @experimental
```
(asset: TimelineAsset, time: number, out: RootPlacement): boolean
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 4f9e756f3..3d50d2ea3 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -17,6 +17,12 @@
// =============================================================================
export { exact, scalar, v2, v3, q, col } from './math';
+// The engine's one curve: a timeline channel, a particle's size over life, and the
+// editor's curve control all author and sample THIS.
+export {
+ InterpType, sampleKeyframes, linearKey,
+ type Keyframe, type Curve,
+} from './math/keyframes';
// =============================================================================
// Localization (i18n)
diff --git a/sdk/src/math/keyframes.ts b/sdk/src/math/keyframes.ts
new file mode 100644
index 000000000..385512f9e
--- /dev/null
+++ b/sdk/src/math/keyframes.ts
@@ -0,0 +1,119 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file keyframes.ts
+ * @brief A curve as authored: keys, tangents, and the one function that samples them.
+ *
+ * There were two curves. A timeline channel had tangents and six interpolations and an
+ * editor that could draw it; a particle's size-over-life had `{t, v}` pairs, straight
+ * lines, and no way to author one at all. Nothing about "a value that changes over a
+ * span" is particular to either, so the shape and the sampler live here and both ask.
+ *
+ * Where `time` runs is the caller's: seconds for a timeline, 0..1 of a particle's life.
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+
+/** How a key reaches the NEXT one. Set per key, so one curve can mix them. */
+export const InterpType = {
+ Hermite: 'hermite',
+ Linear: 'linear',
+ Step: 'step',
+ EaseIn: 'easeIn',
+ EaseOut: 'easeOut',
+ EaseInOut: 'easeInOut',
+} as const;
+
+export type InterpType = (typeof InterpType)[keyof typeof InterpType];
+
+/** One authored point on a curve. Tangents are in value-per-unit-of-time. */
+export interface Keyframe {
+ time: number;
+ value: number;
+ inTangent: number;
+ outTangent: number;
+ interpolation?: InterpType;
+}
+
+// ---------------------------------------------------------------------------
+// Sampling — a 1:1 port of TimelineSystem.cpp::evaluateChannel (keep in lock-step)
+// ---------------------------------------------------------------------------
+
+function hermite(p0: number, p1: number, m0: number, m1: number, t: number): number {
+ const t2 = t * t;
+ const t3 = t2 * t;
+ const h00 = 2 * t3 - 3 * t2 + 1;
+ const h10 = t3 - 2 * t2 + t;
+ const h01 = -2 * t3 + 3 * t2;
+ const h11 = t3 - t2;
+ return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1;
+}
+
+function easeIn(t: number): number {
+ return t * t;
+}
+
+function easeOut(t: number): number {
+ return 1 - (1 - t) * (1 - t);
+}
+
+function easeInOut(t: number): number {
+ return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
+}
+
+/**
+ * @brief The value @p keys hold at @p at. Endpoints CLAMP — a curve states what it
+ * states and nothing beyond, which is what lets a caller sample any time.
+ *
+ * @details Keys are expected in ascending time; an empty curve is 0 and a single key is
+ * that key everywhere. Hermite is the default: a key states tangents, so
+ * ignoring them would be a silent straight line.
+ */
+export function sampleKeyframes(keys: readonly Keyframe[], at: number): number {
+ if (!keys || keys.length === 0) return 0;
+ if (keys.length === 1) return keys[0].value;
+
+ if (at <= keys[0].time) return keys[0].value;
+ if (at >= keys[keys.length - 1].time) return keys[keys.length - 1].value;
+
+ let i = 0;
+ while (i < keys.length - 1 && keys[i + 1].time <= at) i++;
+
+ const k0 = keys[i];
+ const k1 = keys[i + 1];
+ const dt = k1.time - k0.time;
+ if (dt <= 0) return k0.value;
+
+ const t = (at - k0.time) / dt;
+
+ switch (k0.interpolation) {
+ case InterpType.Linear:
+ return k0.value + (k1.value - k0.value) * t;
+ case InterpType.Step:
+ return k0.value;
+ case InterpType.EaseIn:
+ return k0.value + (k1.value - k0.value) * easeIn(t);
+ case InterpType.EaseOut:
+ return k0.value + (k1.value - k0.value) * easeOut(t);
+ case InterpType.EaseInOut:
+ return k0.value + (k1.value - k0.value) * easeInOut(t);
+ case InterpType.Hermite:
+ default:
+ return hermite(k0.value, k1.value, k0.outTangent * dt, k1.inTangent * dt, t);
+ }
+}
+
+/**
+ * @brief A curve as a component or asset carries it.
+ * @details A named shape rather than a bare array so a field can say "this is a curve"
+ * and an editor can offer a curve to author it.
+ */
+export interface Curve {
+ keys: Keyframe[];
+}
+
+/** A key at @p time with straight lines either side — what a hand-written curve wants. */
+export function linearKey(time: number, value: number): Keyframe {
+ return { time, value, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear };
+}
diff --git a/sdk/src/particle/curve.ts b/sdk/src/particle/curve.ts
index fca89e90c..9fac877eb 100644
--- a/sdk/src/particle/curve.ts
+++ b/sdk/src/particle/curve.ts
@@ -2,51 +2,35 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file curve.ts
- * @brief Scalar over-life curve + LUT baking (the size-over-life sibling of
- * gradient.ts). The editor authors a curve (points over [0,1]); this
- * bakes it to a fixed scalar lookup table the C++ particle sim samples by
- * normalized particle age. Same "TS bakes, C++ samples" keystone.
+ * @brief Baking a size-over-life curve into the LUT the C++ sim samples.
+ *
+ * The curve is the engine's one curve (math/keyframes), so the editor's curve control
+ * authors exactly what the sim samples. Time runs 0..1 over a particle's life. Same
+ * "TS bakes, C++ samples" keystone as gradient.ts.
*/
import { GRADIENT_LUT_SIZE } from './gradient';
+import { sampleKeyframes, type Curve } from '../math/keyframes';
-export interface CurveKey {
- /** Position along life, 0..1. */
- t: number;
- /** Value at this key (size-over-life: a multiplier of the particle's start size). */
- v: number;
-}
-
-export interface Curve {
- keys: CurveKey[];
-}
-
-function sampleCurve(sorted: CurveKey[], t: number): number {
- const first = sorted[0];
- if (t <= first.t) return first.v;
- const last = sorted[sorted.length - 1];
- if (t >= last.t) return last.v;
- for (let i = 0; i < sorted.length - 1; i++) {
- const a = sorted[i];
- const b = sorted[i + 1];
- if (t >= a.t && t <= b.t) {
- const span = b.t - a.t;
- const f = span > 1e-6 ? (t - a.t) / span : 0;
- return a.v + (b.v - a.v) * f;
- }
- }
- return last.v;
-}
+export type { Curve, Keyframe } from '../math/keyframes';
/**
- * Bake a curve into an `n`-sample scalar table over [0,1] (piecewise linear).
+ * Bake a curve into an `n`-sample scalar table over [0,1].
* Returns null for an empty/absent curve — the caller clears the LUT so the sim
* falls back to start/end size + easing.
*/
export function bakeCurve(curve: Curve | null | undefined, n = GRADIENT_LUT_SIZE): Float32Array | null {
const keys = curve?.keys;
if (!keys || keys.length === 0) return null;
- const sorted = [...keys].sort((a, b) => a.t - b.t);
+ // A key that is not a number bakes to NaN, and a particle sized NaN does not draw:
+ // the emitter vanishes with nothing said. Refusing the curve falls back to
+ // start/end size instead, which is wrong but visible — and says so once.
+ if (!keys.every((k) => Number.isFinite(k?.time) && Number.isFinite(k?.value))) {
+ console.warn('[particle] a size curve has keys without finite time/value — ignoring it '
+ + '(a curve is { keys: [{ time, value, inTangent, outTangent }] })');
+ return null;
+ }
+ const sorted = [...keys].sort((a, b) => a.time - b.time);
const out = new Float32Array(n);
- for (let i = 0; i < n; i++) out[i] = sampleCurve(sorted, n > 1 ? i / (n - 1) : 0);
+ for (let i = 0; i < n; i++) out[i] = sampleKeyframes(sorted, n > 1 ? i / (n - 1) : 0);
return out;
}
diff --git a/sdk/src/particle/index.ts b/sdk/src/particle/index.ts
index 42a919d26..6fcd8da4d 100644
--- a/sdk/src/particle/index.ts
+++ b/sdk/src/particle/index.ts
@@ -3,4 +3,4 @@
export { Particle, ParticleAPI } from './ParticleAPI';
export { ParticlePlugin, particlePlugin } from './ParticlePlugin';
export { bakeGradient, GRADIENT_LUT_SIZE, type Gradient, type GradientStop } from './gradient';
-export { bakeCurve, type Curve, type CurveKey } from './curve';
+export { bakeCurve, type Curve, type Keyframe } from './curve';
diff --git a/sdk/src/timeline/TimelineEvaluator.ts b/sdk/src/timeline/TimelineEvaluator.ts
index 34fbd68d3..93a3cb472 100644
--- a/sdk/src/timeline/TimelineEvaluator.ts
+++ b/sdk/src/timeline/TimelineEvaluator.ts
@@ -20,7 +20,8 @@
* runtime and the editor preview bridge.
*/
-import { TrackType, InterpType, WrapMode, type TimelineAsset, type PropertyChannel } from './TimelineTypes';
+import { TrackType, WrapMode, type TimelineAsset, type PropertyChannel } from './TimelineTypes';
+import { sampleKeyframes } from '../math/keyframes';
import { setNestedProperty, resolveChildEntity } from './TimelineRuntime';
import { getComponent, type AnyComponentDef } from '../ecs/component';
import type { Pose, PoseTrack, PoseWorld } from '../animation/pose';
@@ -30,66 +31,9 @@ import type { World } from '../ecs/world';
const RAD2DEG = 180 / Math.PI;
-// ---------------------------------------------------------------------------
-// Core math — 1:1 port of TimelineSystem.cpp (keep in lock-step)
-// ---------------------------------------------------------------------------
-
-function hermite(p0: number, p1: number, m0: number, m1: number, t: number): number {
- const t2 = t * t;
- const t3 = t2 * t;
- const h00 = 2 * t3 - 3 * t2 + 1;
- const h10 = t3 - 2 * t2 + t;
- const h01 = -2 * t3 + 3 * t2;
- const h11 = t3 - t2;
- return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1;
-}
-
-function easeIn(t: number): number {
- return t * t;
-}
-
-function easeOut(t: number): number {
- return 1 - (1 - t) * (1 - t);
-}
-
-function easeInOut(t: number): number {
- return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
-}
-
/** Evaluate a single property channel at `time` (seconds). Endpoints clamp. */
export function evaluateChannel(channel: PropertyChannel, time: number): number {
- const kfs = channel.keyframes;
- if (!kfs || kfs.length === 0) return 0;
- if (kfs.length === 1) return kfs[0].value;
-
- if (time <= kfs[0].time) return kfs[0].value;
- if (time >= kfs[kfs.length - 1].time) return kfs[kfs.length - 1].value;
-
- let i = 0;
- while (i < kfs.length - 1 && kfs[i + 1].time <= time) i++;
-
- const k0 = kfs[i];
- const k1 = kfs[i + 1];
- const dt = k1.time - k0.time;
- if (dt <= 0) return k0.value;
-
- const t = (time - k0.time) / dt;
-
- switch (k0.interpolation) {
- case InterpType.Linear:
- return k0.value + (k1.value - k0.value) * t;
- case InterpType.Step:
- return k0.value;
- case InterpType.EaseIn:
- return k0.value + (k1.value - k0.value) * easeIn(t);
- case InterpType.EaseOut:
- return k0.value + (k1.value - k0.value) * easeOut(t);
- case InterpType.EaseInOut:
- return k0.value + (k1.value - k0.value) * easeInOut(t);
- case InterpType.Hermite:
- default:
- return hermite(k0.value, k1.value, k0.outTangent * dt, k1.inTangent * dt, t);
- }
+ return sampleKeyframes(channel.keyframes, time);
}
/** Map an absolute time through the clip's wrap mode (for forward playback). */
diff --git a/sdk/src/timeline/TimelineTypes.ts b/sdk/src/timeline/TimelineTypes.ts
index e90df885b..dc6625c39 100644
--- a/sdk/src/timeline/TimelineTypes.ts
+++ b/sdk/src/timeline/TimelineTypes.ts
@@ -59,24 +59,11 @@ export const TrackType = {
export type TrackType = (typeof TrackType)[keyof typeof TrackType];
-export const InterpType = {
- Hermite: 'hermite',
- Linear: 'linear',
- Step: 'step',
- EaseIn: 'easeIn',
- EaseOut: 'easeOut',
- EaseInOut: 'easeInOut',
-} as const;
-
-export type InterpType = (typeof InterpType)[keyof typeof InterpType];
-
-export interface Keyframe {
- time: number;
- value: number;
- inTangent: number;
- outTangent: number;
- interpolation?: InterpType;
-}
+// A channel's keys are the engine's ONE curve shape — see math/keyframes. Re-exported
+// rather than restated: a timeline that spelled its own would drift from what the
+// particle system and the editor's curve view sample.
+import { InterpType, type Keyframe } from '../math/keyframes';
+export { InterpType, type Keyframe };
export interface PropertyChannel {
property: string;
diff --git a/sdk/tests/curve.test.ts b/sdk/tests/curve.test.ts
index 21930e5f2..5926f230f 100644
--- a/sdk/tests/curve.test.ts
+++ b/sdk/tests/curve.test.ts
@@ -1,8 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import { bakeCurve } from '../src/particle/curve';
import { GRADIENT_LUT_SIZE } from '../src/particle/gradient';
+import { InterpType, linearKey } from '../src/math/keyframes';
describe('bakeCurve', () => {
it('returns null for an empty or absent curve (sim falls back to start/end)', () => {
@@ -11,16 +12,54 @@ describe('bakeCurve', () => {
});
it('bakes N scalar samples, piecewise-linear between keys', () => {
- const lut = bakeCurve({ keys: [{ t: 0, v: 1 }, { t: 1, v: 0 }] })!;
+ const lut = bakeCurve({ keys: [linearKey(0, 1), linearKey(1, 0)] })!;
expect(lut.length).toBe(GRADIENT_LUT_SIZE);
- expect(lut[0]).toBeCloseTo(1, 5); // v=1 at t=0
- expect(lut[GRADIENT_LUT_SIZE - 1]).toBeCloseTo(0, 5); // v=0 at t=1
- expect(lut[Math.round((GRADIENT_LUT_SIZE - 1) / 2)]).toBeCloseTo(0.5, 1); // midpoint
+ expect(lut[0]).toBeCloseTo(1, 5);
+ expect(lut[GRADIENT_LUT_SIZE - 1]).toBeCloseTo(0, 5);
+ expect(lut[Math.round((GRADIENT_LUT_SIZE - 1) / 2)]).toBeCloseTo(0.5, 1);
});
it('clamps before the first key / after the last + sorts unordered keys', () => {
- const lut = bakeCurve({ keys: [{ t: 1, v: 0.2 }, { t: 0.5, v: 1 }] })!;
- expect(lut[0]).toBeCloseTo(1, 5); // before the first sorted key (t=0.5) holds its value
+ const lut = bakeCurve({ keys: [linearKey(1, 0.2), linearKey(0.5, 1)] })!;
+ expect(lut[0]).toBeCloseTo(1, 5);
expect(lut[GRADIENT_LUT_SIZE - 1]).toBeCloseTo(0.2, 5);
});
+
+ // A particle curve can ease. The MIDPOINT is what separates the two — both agree
+ // at the ends whatever the interpolation says.
+ it('eases when a key says to, where a linear key would not', () => {
+ const mid = Math.round((GRADIENT_LUT_SIZE - 1) / 2);
+ const linear = bakeCurve({ keys: [linearKey(0, 0), linearKey(1, 1)] })!;
+ const eased = bakeCurve({
+ keys: [
+ { time: 0, value: 0, inTangent: 0, outTangent: 0, interpolation: InterpType.EaseIn },
+ { time: 1, value: 1, inTangent: 0, outTangent: 0, interpolation: InterpType.EaseIn },
+ ],
+ })!;
+ expect(linear[mid]).toBeCloseTo(0.5, 1);
+ expect(eased[mid]).toBeCloseTo(0.25, 1);
+ expect(eased[0]).toBeCloseTo(linear[0], 5);
+ expect(eased[GRADIENT_LUT_SIZE - 1]).toBeCloseTo(linear[GRADIENT_LUT_SIZE - 1], 5);
+ });
+
+ // A curve whose keys are not numbers must not bake NaN: a particle sized NaN draws
+ // nothing, so the emitter would disappear with nothing said. Refusing it falls back
+ // to start/end — wrong, but visible.
+ it('refuses keys that are not finite rather than baking NaN', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ expect(bakeCurve({ keys: [{ t: 0, v: 1 }, { t: 1, v: 0 }] } as never)).toBeNull();
+ expect(warn).toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it('holds a value flat until the next key when a key steps', () => {
+ const lut = bakeCurve({
+ keys: [
+ { time: 0, value: 0.25, inTangent: 0, outTangent: 0, interpolation: InterpType.Step },
+ { time: 1, value: 1, inTangent: 0, outTangent: 0, interpolation: InterpType.Step },
+ ],
+ })!;
+ expect(lut[Math.round((GRADIENT_LUT_SIZE - 1) * 0.9)]).toBeCloseTo(0.25, 5);
+ expect(lut[GRADIENT_LUT_SIZE - 1]).toBeCloseTo(1, 5);
+ });
});
diff --git a/sdk/tests/keyframes.test.ts b/sdk/tests/keyframes.test.ts
new file mode 100644
index 000000000..0f014eecf
--- /dev/null
+++ b/sdk/tests/keyframes.test.ts
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file keyframes.test.ts — the one curve both a timeline and a particle sample.
+ *
+ * These hold the behaviour the two shapes disagreed about before they were one:
+ * a timeline had tangents and six interpolations, a particle curve had straight
+ * lines. Whichever a caller relies on, it is decided here now.
+ */
+import { describe, it, expect } from 'vitest';
+import { sampleKeyframes, linearKey, InterpType, type Keyframe } from '../src/math/keyframes';
+import { evaluateChannel } from '../src/timeline/TimelineEvaluator';
+
+const key = (time: number, value: number, interpolation?: InterpType, tangents = 0): Keyframe =>
+ ({ time, value, inTangent: tangents, outTangent: tangents, interpolation });
+
+describe('sampleKeyframes', () => {
+ it('answers 0 for nothing and the lone value for one key', () => {
+ expect(sampleKeyframes([], 0.5)).toBe(0);
+ expect(sampleKeyframes([linearKey(3, 7)], -99)).toBe(7);
+ expect(sampleKeyframes([linearKey(3, 7)], 99)).toBe(7);
+ });
+
+ // Endpoints CLAMP rather than extrapolate: a curve states what it states, which is
+ // what lets a particle at age 1.0 and a timeline past its last key both be sampled.
+ it('clamps outside the authored span', () => {
+ const keys = [linearKey(1, 10), linearKey(2, 20)];
+ expect(sampleKeyframes(keys, 0)).toBe(10);
+ expect(sampleKeyframes(keys, 0.5)).toBe(10);
+ expect(sampleKeyframes(keys, 5)).toBe(20);
+ expect(sampleKeyframes(keys, 2.5)).toBe(20);
+ });
+
+ it('interpolates the way the LEFT key says, per segment', () => {
+ const keys = [key(0, 0, InterpType.Step), key(1, 10, InterpType.Linear), key(2, 20)];
+ expect(sampleKeyframes(keys, 0.9)).toBe(0);
+ expect(sampleKeyframes(keys, 1.5)).toBeCloseTo(15, 5);
+ });
+
+ it('eases in, out and both, each bending the way its name says', () => {
+ const at = (kind: InterpType) => sampleKeyframes([key(0, 0, kind), key(1, 1, kind)], 0.5);
+ expect(at(InterpType.Linear)).toBeCloseTo(0.5, 5);
+ expect(at(InterpType.EaseIn)).toBeCloseTo(0.25, 5);
+ expect(at(InterpType.EaseOut)).toBeCloseTo(0.75, 5);
+ expect(at(InterpType.EaseInOut)).toBeCloseTo(0.5, 5);
+ });
+
+ it('uses the tangents by default, and a zero tangent is not a straight line', () => {
+ expect(sampleKeyframes([key(0, 0), key(1, 1)], 0.5)).toBeCloseTo(0.5, 5);
+ // Hermite with flat tangents eases at both ends, so it is BELOW the straight
+ // line early on. Equal here would mean the default silently became linear.
+ const hermiteQuarter = sampleKeyframes([key(0, 0), key(1, 1)], 0.25);
+ const linearQuarter = sampleKeyframes([key(0, 0, InterpType.Linear), key(1, 1)], 0.25);
+ expect(hermiteQuarter).toBeLessThan(linearQuarter);
+ });
+
+ // The tangent's VALUE has to reach the result. Every other case here passes on a
+ // sampler that read the tangents as zero — it would just be a different smooth curve.
+ it('gives a steeper tangent a higher value early in the segment', () => {
+ const flat = sampleKeyframes([key(0, 0, undefined, 0), key(1, 1, undefined, 0)], 0.25);
+ const steep = sampleKeyframes([key(0, 0, undefined, 2), key(1, 1, undefined, 2)], 0.25);
+ expect(steep).toBeGreaterThan(flat);
+ });
+
+ // Tangents are value-per-unit-TIME, so the sampler scales them BY the segment: the
+ // same shape over three times the span, at a third the slope, must sample alike.
+ // A one-unit segment cannot tell scaled from unscaled, so neither of these is one.
+ it('scales tangents by the segment, so the same shape samples alike at any width', () => {
+ // Steeper than the straight line between the keys (which is slope 1 over the
+ // narrow span) — at slope 1 exactly, hermite IS the straight line and this
+ // could not tell a scaled tangent from an unscaled one.
+ const narrow = sampleKeyframes([key(0, 0, undefined, 2), key(1, 1, undefined, 2)], 0.25);
+ const wide = sampleKeyframes([key(0, 0, undefined, 2 / 3), key(3, 1, undefined, 2 / 3)], 0.75);
+ expect(wide).toBeCloseTo(narrow, 5);
+ expect(narrow).not.toBeCloseTo(0.25, 2);
+ });
+
+ it('is what a timeline channel is evaluated by', () => {
+ const keyframes = [key(0, 0, InterpType.Linear), key(2, 8, InterpType.Linear)];
+ expect(evaluateChannel({ property: 'x', keyframes }, 1)).toBe(sampleKeyframes(keyframes, 1));
+ expect(evaluateChannel({ property: 'x', keyframes }, 1)).toBeCloseTo(4, 5);
+ });
+
+ it('holds a segment of zero width rather than dividing by it', () => {
+ expect(sampleKeyframes([linearKey(1, 5), linearKey(1, 9)], 1)).toBe(5);
+ });
+});