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.

feat: particle color-over-life gradients (end to end)

esengine310192d20e4a
diff --git a/desktop/electron/extractSchemas.ts b/desktop/electron/extractSchemas.ts
index 1ca34ccf5..d17b2222d 100644
--- a/desktop/electron/extractSchemas.ts
+++ b/desktop/electron/extractSchemas.ts
@@ -65,6 +65,7 @@ export interface SerializedFieldMeta {
enumSource?: string;
flags?: Array<{ label: string; value: number }>;
bitmask?: { bits?: number; source?: string };
+ gradient?: boolean;
min?: number;
max?: number;
step?: number;
@@ -212,6 +213,7 @@ function pickFieldMeta(
if (meta.enumSource) m.enumSource = meta.enumSource;
if (meta.flags && meta.flags.length) m.flags = meta.flags.map((o) => ({ ...o }));
if (meta.bitmask) m.bitmask = { ...meta.bitmask };
+ if (meta.gradient) m.gradient = true;
if (meta.min != null) m.min = meta.min;
if (meta.max != null) m.max = meta.max;
if (meta.step != null) m.step = meta.step;
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index cc8cad9aa..1464f17ac 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -99,6 +99,8 @@ export function toModelValue(
case 'color':
// The hex carries alpha (#rrggbbaa), so it fully describes RGBA.
return { ...(cur[key] as object), ...hexToRgba(String(value)) };
+ case 'gradient':
+ return value; // a structural { stops: [...] } object — stored as-is
default:
return value;
}
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 7adc2d37c..b9ffd3b91 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { getAllRegisteredComponents, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentFieldMeta } from 'esengine';
import type { App, SceneData } from 'esengine';
-import type { NodeKind, InspectorField, EnumOption } from '@/types';
+import type { NodeKind, InspectorField, EnumOption, GradientValue } from '@/types';
type SceneEntityLike = SceneData['entities'][number];
@@ -191,6 +191,7 @@ export interface UserFieldMeta {
enumSource?: string;
flags?: EnumOption[];
bitmask?: { bits?: number; source?: string };
+ gradient?: boolean;
min?: number;
max?: number;
step?: number;
@@ -268,6 +269,7 @@ export function fieldMetaFor(compType: string, key: string): UserFieldMeta | nul
enumSource: fromDef.enumSource,
flags: fromDef.flags?.map((o) => ({ label: o.label, value: o.value })),
bitmask: fromDef.bitmask,
+ gradient: fromDef.gradient,
min: fromDef.min,
max: fromDef.max,
step: fromDef.step,
@@ -331,6 +333,9 @@ function fieldFor(
let field: InspectorField | null;
if (at) {
field = { key, label: prettyLabel(key), type: 'asset', value: typeof value === 'string' ? value : 0, assetType: at };
+ } else if (meta?.gradient) {
+ const g = value && typeof value === 'object' && Array.isArray((value as GradientValue).stops) ? (value as GradientValue) : { stops: [] };
+ field = { key, label: prettyLabel(key), type: 'gradient', value: g };
} else if (meta?.bitmask) {
field = { key, label: prettyLabel(key), type: 'flags', value: Number(value) || 0, options: bitmaskOptions(meta.bitmask) };
} else if (meta?.flags && meta.flags.length) {
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 7d9c40ba7..cd66a5f0f 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -42,7 +42,7 @@ import { ProjectStore } from '@/project/ProjectStore';
import { ContextMenu } from '@/components/Menu';
import { Popover, usePopover } from '@/components/Popover';
import { AddComponentMenu } from '@/components/AddComponentMenu';
-import type { InspectorComponent, InspectorField, InspectorFieldValue, EntityId, NodeKind, EnumOption, AssetType } from '@/types';
+import type { InspectorComponent, InspectorField, InspectorFieldValue, EntityId, NodeKind, EnumOption, AssetType, GradientValue, GradientStop } from '@/types';
const AXES = ['x', 'y', 'z'];
const fmt = (n: number) => String(Math.round(n * 1000) / 1000);
@@ -666,6 +666,128 @@ function ColorControl({
);
}
+const rgbaCss = (c: { r: number; g: number; b: number; a: number }) =>
+ `rgba(${Math.round(c.r * 255)},${Math.round(c.g * 255)},${Math.round(c.b * 255)},${c.a})`;
+
+// Interpolate a gradient's color at t (matches the runtime bake), for new stops.
+function sampleStops(stops: GradientStop[], t: number): GradientStop['color'] {
+ if (stops.length === 0) return { r: 1, g: 1, b: 1, a: 1 };
+ const sorted = [...stops].sort((a, b) => a.t - b.t);
+ if (t <= sorted[0].t) return { ...sorted[0].color };
+ const last = sorted[sorted.length - 1];
+ if (t >= last.t) return { ...last.color };
+ 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 f = b.t - a.t > 1e-6 ? (t - a.t) / (b.t - a.t) : 0;
+ return {
+ r: a.color.r + (b.color.r - a.color.r) * f,
+ g: a.color.g + (b.color.g - a.color.g) * f,
+ b: a.color.b + (b.color.b - a.color.b) * f,
+ a: a.color.a + (b.color.a - a.color.a) * f,
+ };
+ }
+ }
+ return { ...last.color };
+}
+
+// A color-over-life gradient editor: a preview bar with draggable stops; click the
+// bar to add a stop, select one to edit its color (the themed picker) or delete it.
+// Empty ⇒ the particle falls back to start/end + easing (the runtime bake skips it).
+function GradientControl({
+ value,
+ onBegin,
+ onEnd,
+ onChange,
+}: ControlGesture & { value: GradientValue; onChange: (v: GradientValue) => void }) {
+ const bar = useRef<HTMLDivElement>(null);
+ const drag = useRef<number | null>(null);
+ const [sel, setSel] = useState(0);
+ const stops = value.stops ?? [];
+ const ordered = [...stops].sort((a, b) => a.t - b.t);
+ const css = stops.length
+ ? `linear-gradient(90deg, ${ordered.map((s) => `${rgbaCss(s.color)} ${Math.round(s.t * 100)}%`).join(', ')})`
+ : 'var(--inset)';
+
+ const commit = (next: GradientStop[]) => onChange({ stops: next });
+ const tFromX = (clientX: number) => {
+ const r = bar.current?.getBoundingClientRect();
+ return r && r.width ? Math.max(0, Math.min(1, (clientX - r.left) / r.width)) : 0;
+ };
+ const selColor = stops[sel]?.color;
+
+ return (
+ <div className="grad">
+ <div
+ ref={bar}
+ className="grad-bar"
+ onPointerDown={(e) => {
+ if (e.target !== bar.current && !(e.target as HTMLElement).classList.contains('grad-fill')) return;
+ const t = tFromX(e.clientX);
+ onBegin?.();
+ const next = [...stops, { t, color: sampleStops(stops, t) }];
+ commit(next);
+ setSel(next.length - 1);
+ onEnd?.();
+ }}
+ >
+ <span className="grad-fill" style={{ background: css }} />
+ {stops.map((s, i) => (
+ <span
+ key={i}
+ className={`grad-stop${i === sel ? ' on' : ''}`}
+ style={{ left: `${s.t * 100}%`, background: rgbaCss(s.color) }}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ setSel(i);
+ drag.current = i;
+ onBegin?.();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ }}
+ onPointerMove={(e) => {
+ if (drag.current !== i) return;
+ commit(stops.map((st, j) => (j === i ? { ...st, t: tFromX(e.clientX) } : st)));
+ }}
+ onPointerUp={(e) => {
+ if (drag.current !== i) return;
+ drag.current = null;
+ e.currentTarget.releasePointerCapture?.(e.pointerId);
+ onEnd?.();
+ }}
+ />
+ ))}
+ </div>
+ {selColor && (
+ <div className="grad-edit">
+ <ColorControl
+ value={rgbaToHex8(selColor.r, selColor.g, selColor.b, selColor.a)}
+ onBegin={onBegin}
+ onEnd={onEnd}
+ onChange={(hex) => {
+ const c = hexToRgba(hex);
+ commit(stops.map((st, j) => (j === sel ? { ...st, color: c } : st)));
+ }}
+ />
+ <button
+ type="button"
+ className="grad-del"
+ title="Remove stop"
+ onClick={() => {
+ onBegin?.();
+ commit(stops.filter((_, j) => j !== sel));
+ setSel(0);
+ onEnd?.();
+ }}
+ >
+ <X size={11} strokeWidth={2} />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
const isImageAsset = (t: AssetType): boolean => t === 'texture' || t === 'sprite';
// An asset-ref field: a drop target showing the bound asset, PLUS a pick popover
@@ -792,7 +914,7 @@ function AssetControl({
// A field write override (the live "Game" inspector routes edits to the realm
// instead of the undoable SceneCommands path). When set, gestures are no-ops.
-type FieldWrite = (key: string, type: InspectorField['type'], value: number | boolean | string | number[]) => void;
+type FieldWrite = (key: string, type: InspectorField['type'], value: number | boolean | string | number[] | GradientValue) => void;
function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp: string; field: InspectorField; write?: FieldWrite }) {
const ranged = field.min != null || field.max != null;
@@ -805,7 +927,7 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp
};
// An edit fans out to every selected entity (the open gesture coalesces them
// into one undo step); the live "Game" inspector routes to the realm instead.
- const apply = (value: number | boolean | string | number[]) => {
+ const apply = (value: number | boolean | string | number[] | GradientValue) => {
const v = ranged && typeof value === 'number' ? clamp(value) : value;
if (write) return write(field.key, field.type, v);
for (const e of entities) SceneCommands.setField(e, comp, field.key, field.type, v as never);
@@ -880,6 +1002,9 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp
case 'color':
control = <ColorControl value={field.value as string} onBegin={begin} onEnd={end} onChange={apply} />;
break;
+ case 'gradient':
+ control = <GradientControl value={field.value as GradientValue} onBegin={begin} onEnd={end} onChange={apply} />;
+ break;
case 'asset':
control = (
<AssetControl
diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.css
index 9d5414ad1..a32f0d75f 100644
--- a/desktop/src/theme/inspector.css
+++ b/desktop/src/theme/inspector.css
@@ -134,6 +134,18 @@
.cp-bar-dot { position: absolute; top: 50%; width: 14px; height: 14px; border-radius: 50%; background: #fff; border: 1px solid rgba(0,0,0,.4); box-shadow: var(--shadow-1); transform: translate(-50%,-50%); pointer-events: none; }
.cp-hex { width: 100%; height: 24px; background: var(--inset); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 0 8px; color: var(--text); font-family: var(--mono); font-size: var(--fs-sm); outline: none; }
.cp-hex:focus { border-color: var(--acc); box-shadow: 0 0 0 2px var(--acc-soft); }
+
+/* color-over-life gradient editor (a bar of draggable stops + the selected stop's color) */
+.grad { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }
+.grad-bar { position: relative; height: 22px; border-radius: var(--r-sm); border: 1px solid var(--border); cursor: copy;
+ background-image: linear-gradient(45deg,#777 25%,transparent 25%),linear-gradient(-45deg,#777 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#777 75%),linear-gradient(-45deg,transparent 75%,#777 75%);
+ background-size: 8px 8px; background-position: 0 0,0 4px,4px -4px,-4px 0; background-color: #fff; }
+.grad-fill { position: absolute; inset: 0; border-radius: inherit; }
+.grad-stop { position: absolute; top: -3px; width: 10px; height: calc(100% + 6px); transform: translateX(-50%); border: 2px solid #fff; border-radius: 3px; box-shadow: 0 0 0 1px rgba(0,0,0,.55); cursor: ew-resize; box-sizing: border-box; }
+.grad-stop.on { border-color: var(--acc-hi); box-shadow: 0 0 0 1px var(--acc), var(--shadow-1); z-index: 1; }
+.grad-edit { display: flex; align-items: center; gap: 6px; }
+.grad-del { width: 22px; height: 22px; display: grid; place-items: center; color: var(--text-mute); border: 1px solid var(--border-line); border-radius: var(--r-sm); flex-shrink: 0; transition: color var(--t-fast), border-color var(--t-fast); }
+.grad-del:hover { color: var(--error); border-color: var(--error); }
.slider { flex: 1; height: 6px; background: var(--inset); border-radius: var(--r-pill); position: relative; cursor: ew-resize; touch-action: none; }
.slider .fill { position: absolute; left: 0; top: 0; bottom: 0; background: var(--acc); border-radius: var(--r-pill); }
.slider .thumb { position: absolute; top: 50%; width: 11px; height: 11px; border-radius: 50%; background: var(--text); transform: translate(-50%,-50%); box-shadow: var(--shadow-1); }
diff --git a/desktop/src/timeline/TimelineRecorder.ts b/desktop/src/timeline/TimelineRecorder.ts
index cd17454d6..99776e777 100644
--- a/desktop/src/timeline/TimelineRecorder.ts
+++ b/desktop/src/timeline/TimelineRecorder.ts
@@ -43,7 +43,7 @@ function scalarFor(value: InspectorFieldValue, property: string, key: string): n
if (i == null) return null;
if (Array.isArray(value)) return typeof value[i] === 'number' ? (value[i] as number) : null;
if (value && typeof value === 'object') {
- const v = (value as Record<string, unknown>)[suffix];
+ const v = (value as unknown as Record<string, unknown>)[suffix];
return typeof v === 'number' ? v : null;
}
return null;
diff --git a/desktop/src/types.ts b/desktop/src/types.ts
index d96389bac..3c44779e5 100644
--- a/desktop/src/types.ts
+++ b/desktop/src/types.ts
@@ -37,6 +37,7 @@ export type InspectorFieldType =
| 'color'
| 'enum' // an int field with named options, shown as a dropdown
| 'flags' // an int bitmask, shown as a multi-select of its bits
+ | 'gradient' // a color-over-life gradient ({ stops: [...] })
| 'asset'; // a texture/material/font/... ref (@uuid: string, or 0 for none)
/** A dropdown option for an `enum` field: the label shown, the int stored. */
@@ -45,12 +46,23 @@ export interface EnumOption {
value: number;
}
+/** One stop of a `gradient` field: a 0..1 position + an RGBA color (0..1 channels). */
+export interface GradientStop {
+ t: number;
+ color: { r: number; g: number; b: number; a: number };
+}
+/** A `gradient` field's value — color stops over [0,1]. */
+export interface GradientValue {
+ stops: GradientStop[];
+}
+
export type InspectorFieldValue =
| number
| boolean
| string
| [number, number]
- | [number, number, number];
+ | [number, number, number]
+ | GradientValue;
export interface InspectorField {
/** key in the component data object */
diff --git a/desktop/tests/inspector-model.test.ts b/desktop/tests/inspector-model.test.ts
index 21eb10e82..174ddc58f 100644
--- a/desktop/tests/inspector-model.test.ts
+++ b/desktop/tests/inspector-model.test.ts
@@ -292,6 +292,48 @@ describe('Unknown-component inspector (schemas.json consumer)', () => {
});
});
+describe('Color gradient field (particle color-over-life)', () => {
+ it("renders ParticleEmitter.colorGradient as a 'gradient' field that round-trips", () => {
+ const grad = { stops: [{ t: 0, color: { r: 1, g: 0, b: 0, a: 1 } }, { t: 1, color: { r: 0, g: 0, b: 1, a: 0 } }] };
+ const S = EditorSession.create();
+ S.model.adopt(
+ {
+ version: '1.0',
+ name: 'p',
+ entities: [{ id: 1, name: 'P', parent: null, children: [], components: [{ type: 'ParticleEmitter', data: { colorGradient: grad } }] }],
+ } as unknown as SceneData,
+ new Map([[1, 1]]),
+ );
+ const field = () =>
+ S.query.readInspector(1).find((c) => c.name === 'ParticleEmitter')!.fields.find((f) => f.key === 'colorGradient')!;
+ const g = field();
+ expect(g.type).toBe('gradient');
+ expect((g.value as { stops: unknown[] }).stops.length).toBe(2);
+
+ S.commands.setField(1, 'ParticleEmitter', 'colorGradient', 'gradient', {
+ stops: [{ t: 0.5, color: { r: 0, g: 1, b: 0, a: 1 } }],
+ } as never);
+ const after = field().value as { stops: { t: number }[] };
+ expect(after.stops.length).toBe(1);
+ expect(after.stops[0].t).toBe(0.5);
+ });
+
+ it('an empty gradient field reads as empty stops (sim falls back to start/end)', () => {
+ const S = EditorSession.create();
+ S.model.adopt(
+ {
+ version: '1.0',
+ name: 'p',
+ entities: [{ id: 1, name: 'P', parent: null, children: [], components: [{ type: 'ParticleEmitter', data: {} }] }],
+ } as unknown as SceneData,
+ new Map([[1, 1]]),
+ );
+ const g = S.query.readInspector(1).find((c) => c.name === 'ParticleEmitter')!.fields.find((f) => f.key === 'colorGradient')!;
+ expect(g.type).toBe('gradient');
+ expect((g.value as { stops: unknown[] }).stops).toEqual([]);
+ });
+});
+
describe('Sorting-layer enum source (render layer)', () => {
afterEach(() => setEnumSource('sortingLayers', null));
function spriteScene(layer: number): SceneData {
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index d6f60abb4..89384b4fa 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -42,6 +42,8 @@ export interface FieldMeta {
enumSource?: string;
/** Render as a bitmask multi-select; each option is a single bit. */
flags?: ReadonlyArray<{ label: string; value: number }>;
+ /** Render as a color-gradient editor (the field value is `{ stops: [...] }`). */
+ gradient?: boolean;
/**
* Render as a bitmask whose bit LABELS are resolved by the editor (e.g. named
* collision layers from project settings) rather than fixed here. `bits` is the
@@ -749,10 +751,16 @@ export interface ParticleEmitterData {
material: number;
simulationSpace: number;
enabled: boolean;
+ /**
+ * Color-over-life gradient (authored stops). When it has stops it overrides
+ * startColor/endColor + colorEasing. Not a C++ field — baked to a LUT the sim
+ * samples (see particlePlugin's scene codec). Empty ⇒ start/end fallback.
+ */
+ colorGradient: { stops: { t: number; color: Color }[] };
}
export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitter',
- metaDefaults<ParticleEmitterData>('ParticleEmitter'),
+ metaDefaults<ParticleEmitterData>('ParticleEmitter', { colorGradient: { stops: [] } }),
{
// A large component — organized into UE-style property categories.
fields: {
@@ -780,6 +788,7 @@ export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitt
endSizeMin: { min: 0, category: 'Size' },
endSizeMax: { min: 0, category: 'Size' },
sizeEasing: { enum: enumOptions(ParticleEasing), category: 'Size' },
+ colorGradient: { gradient: true, category: 'Color' },
startColor: { category: 'Color' },
endColor: { category: 'Color' },
colorEasing: { enum: enumOptions(ParticleEasing), category: 'Color' },
diff --git a/sdk/src/particle/ParticleAPI.ts b/sdk/src/particle/ParticleAPI.ts
index 9a6e58f9d..10ea38986 100644
--- a/sdk/src/particle/ParticleAPI.ts
+++ b/sdk/src/particle/ParticleAPI.ts
@@ -40,6 +40,28 @@ export class ParticleAPI {
getAliveCount(entity: Entity): number {
return this.module_.particle_getAliveCount?.(entity as number) ?? 0;
}
+
+ /**
+ * Upload an entity's baked color-over-life LUT (an N×4 RGBA Float32Array) so
+ * the sim samples it instead of start/end + easing; pass null to clear. The
+ * data is copied into the wasm heap for the call, then freed.
+ */
+ setColorLut(entity: Entity, lut: Float32Array | null): void {
+ const m = this.module_;
+ if (!m.particle_set_color_lut) return;
+ if (!lut || lut.length === 0) {
+ m.particle_set_color_lut(entity as number, 0, 0);
+ return;
+ }
+ const bytes = lut.length * 4;
+ const ptr = m._malloc(bytes);
+ try {
+ m.HEAPF32.set(lut, ptr / 4);
+ m.particle_set_color_lut(entity as number, ptr, lut.length / 4);
+ } finally {
+ m._free(ptr);
+ }
+ }
}
/** Resource handle for the per-app particle API. */
diff --git a/sdk/src/particle/ParticlePlugin.ts b/sdk/src/particle/ParticlePlugin.ts
index a8aa30e1f..b9f757784 100644
--- a/sdk/src/particle/ParticlePlugin.ts
+++ b/sdk/src/particle/ParticlePlugin.ts
@@ -6,15 +6,38 @@ import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
import { playModeOnly } from '../env';
import type { ESEngineModule, CppRegistry } from '../wasm';
+import { registerSceneComponentCodec } from '../scene';
import { Particle, ParticleAPI } from './ParticleAPI';
+import { bakeGradient, type Gradient } from './gradient';
export class ParticlePlugin implements Plugin {
name = 'particle';
+ /** Entity → authored color-over-life gradient (out-of-band; baked to the C++ LUT). */
+ private readonly gradients_ = new Map<number, Gradient>();
+
build(app: App): void {
const module = app.wasmModule as ESEngineModule;
const registry = app.world.getCppRegistry() as CppRegistry;
- app.insertResource(Particle, new ParticleAPI(module, registry));
+ const api = new ParticleAPI(module, registry);
+ app.insertResource(Particle, api);
+
+ // The color gradient is authored as stops in the component data but isn't a
+ // C++ field — carry it out-of-band and bake it into the sim's LUT on load.
+ const gradients = this.gradients_;
+ registerSceneComponentCodec('ParticleEmitter', {
+ outOfBandFields: ['colorGradient'],
+ importData: (entity, outOfBand) => {
+ const g = outOfBand.colorGradient as Gradient | undefined;
+ api.setColorLut(entity, bakeGradient(g));
+ if (g?.stops?.length) gradients.set(entity, g);
+ else gradients.delete(entity);
+ },
+ exportData: (entity, data) => {
+ const g = gradients.get(entity);
+ if (g) data.colorGradient = g;
+ },
+ });
// Particle advance is gameplay — frozen in editor edit mode, runs in
// play mode / standalone runtime (matches animation/physics/timeline).
diff --git a/sdk/src/particle/gradient.ts b/sdk/src/particle/gradient.ts
new file mode 100644
index 000000000..0842034c8
--- /dev/null
+++ b/sdk/src/particle/gradient.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file gradient.ts
+ * @brief Color gradient (over particle life) + LUT baking. The editor authors a
+ * gradient (color stops); this bakes it to a fixed RGBA lookup table the
+ * C++ particle sim samples by normalized particle age. Curve math lives
+ * here (TS) only — the runtime just indexes the baked table.
+ */
+import type { Color } from '../types';
+
+export interface GradientStop {
+ /** Position along life, 0..1. */
+ t: number;
+ color: Color;
+}
+
+export interface Gradient {
+ stops: GradientStop[];
+}
+
+/** LUT resolution — MUST match the C++ `particle::kColorLutSize`. */
+export const GRADIENT_LUT_SIZE = 32;
+
+function sampleGradient(sorted: GradientStop[], t: number): Color {
+ const first = sorted[0];
+ if (t <= first.t) return first.color;
+ const last = sorted[sorted.length - 1];
+ if (t >= last.t) return last.color;
+ 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 {
+ r: a.color.r + (b.color.r - a.color.r) * f,
+ g: a.color.g + (b.color.g - a.color.g) * f,
+ b: a.color.b + (b.color.b - a.color.b) * f,
+ a: a.color.a + (b.color.a - a.color.a) * f,
+ };
+ }
+ }
+ return last.color;
+}
+
+/**
+ * Bake a gradient into an `n`×4 RGBA table sampled uniformly over [0,1]. Returns
+ * null for an empty/absent gradient — the caller clears the LUT so the particle
+ * sim falls back to start/end + easing.
+ */
+export function bakeGradient(gradient: Gradient | null | undefined, n = GRADIENT_LUT_SIZE): Float32Array | null {
+ const stops = gradient?.stops;
+ if (!stops || stops.length === 0) return null;
+ const sorted = [...stops].sort((a, b) => a.t - b.t);
+ const out = new Float32Array(n * 4);
+ for (let i = 0; i < n; i++) {
+ const c = sampleGradient(sorted, n > 1 ? i / (n - 1) : 0);
+ out[i * 4] = c.r;
+ out[i * 4 + 1] = c.g;
+ out[i * 4 + 2] = c.b;
+ out[i * 4 + 3] = c.a;
+ }
+ return out;
+}
diff --git a/sdk/src/particle/index.ts b/sdk/src/particle/index.ts
index e89978bc9..f99cd5599 100644
--- a/sdk/src/particle/index.ts
+++ b/sdk/src/particle/index.ts
@@ -2,3 +2,4 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
export { Particle, ParticleAPI } from './ParticleAPI';
export { ParticlePlugin, particlePlugin } from './ParticlePlugin';
+export { bakeGradient, GRADIENT_LUT_SIZE, type Gradient, type GradientStop } from './gradient';
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 7a9ef04e3..9c39b7857 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -248,6 +248,8 @@ export interface ESEngineModule {
particle_stop?(registry: CppRegistry, entity: number): void;
particle_reset?(registry: CppRegistry, entity: number): void;
particle_getAliveCount?(entity: number): number;
+ /** Upload (count = LUT size) or clear (count = 0) an entity's baked color-over-life LUT. */
+ particle_set_color_lut?(entity: number, ptr: number, count: number): void;
// Tilemap API
tilemap_initLayer?(entity: number, width: number, height: number,
diff --git a/sdk/tests/gradient.test.ts b/sdk/tests/gradient.test.ts
new file mode 100644
index 000000000..6b5d665f7
--- /dev/null
+++ b/sdk/tests/gradient.test.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { bakeGradient, GRADIENT_LUT_SIZE } from '../src/particle/gradient';
+
+const red = { r: 1, g: 0, b: 0, a: 1 };
+const blue = { r: 0, g: 0, b: 1, a: 0 };
+
+describe('bakeGradient', () => {
+ it('returns null for an empty or absent gradient (sim falls back to start/end)', () => {
+ expect(bakeGradient(null)).toBeNull();
+ expect(bakeGradient({ stops: [] })).toBeNull();
+ });
+
+ it('bakes N×4 RGBA samples spanning the stops', () => {
+ const lut = bakeGradient({ stops: [{ t: 0, color: red }, { t: 1, color: blue }] })!;
+ expect(lut.length).toBe(GRADIENT_LUT_SIZE * 4);
+ // First sample = red (t=0), last = blue (t=1).
+ expect([lut[0], lut[1], lut[2], lut[3]]).toEqual([1, 0, 0, 1]);
+ const n = GRADIENT_LUT_SIZE - 1;
+ expect([lut[n * 4], lut[n * 4 + 1], lut[n * 4 + 2], lut[n * 4 + 3]]).toEqual([0, 0, 1, 0]);
+ // Midpoint linearly interpolates (incl. alpha 1→0).
+ const mid = Math.round(n / 2);
+ expect(lut[mid * 4]).toBeCloseTo(0.5, 1);
+ expect(lut[mid * 4 + 2]).toBeCloseTo(0.5, 1);
+ expect(lut[mid * 4 + 3]).toBeCloseTo(0.5, 1);
+ });
+
+ it('sorts unordered stops and clamps before the first / after the last', () => {
+ const lut = bakeGradient({ stops: [{ t: 1, color: blue }, { t: 0, color: red }] })!;
+ expect([lut[0], lut[2]]).toEqual([1, 0]); // still red at t=0 after sorting
+ });
+});
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index cd90eb4d7..bf7329629 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -330,6 +330,11 @@ u32 particle_getAliveCount(Entity entity) {
if (!g_particleSystem) return 0;
return g_particleSystem->aliveCount(entity);
}
+
+void particle_set_color_lut(Entity entity, uintptr_t ptr, i32 count) {
+ if (!g_particleSystem) return;
+ g_particleSystem->setColorLut(entity, reinterpret_cast<const f32*>(ptr), count);
+}
#endif
void renderer_setStage(i32 stage) {
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index da3536b80..9ffb5cb2b 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -89,6 +89,7 @@ void particle_play(ecs::Registry& registry, Entity entity);
void particle_stop(ecs::Registry& registry, Entity entity);
void particle_reset(ecs::Registry& registry, Entity entity);
u32 particle_getAliveCount(Entity entity);
+void particle_set_color_lut(Entity entity, uintptr_t ptr, i32 count);
#endif
void renderer_setStage(i32 stage);
u32 renderer_createTarget(u32 width, u32 height, i32 flags);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 628a77d5f..baa34c9f9 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -463,6 +463,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("particle_stop", &esengine::particle_stop);
emscripten::function("particle_reset", &esengine::particle_reset);
emscripten::function("particle_getAliveCount", &esengine::particle_getAliveCount);
+ emscripten::function("particle_set_color_lut", &esengine::particle_set_color_lut);
#endif
emscripten::function("renderer_setStage", &esengine::renderer_setStage);
emscripten::function("renderer_createTarget", &esengine::renderer_createTarget);
diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cpp
index f20428a95..27ffcf0d1 100644
--- a/src/esengine/particle/ParticleSystem.cpp
+++ b/src/esengine/particle/ParticleSystem.cpp
@@ -15,6 +15,7 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {
if (!destroyConn_.isConnected()) {
destroyConn_ = registry.onDestroyScoped([this](Entity entity) {
states_.erase(entity);
+ colorLuts_.erase(entity);
});
}
@@ -73,7 +74,8 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {
}
}
- updateParticles(emitter, state, dt);
+ auto lutIt = colorLuts_.find(entity);
+ updateParticles(emitter, state, dt, lutIt != colorLuts_.end() ? &lutIt->second : nullptr);
}
}
@@ -103,6 +105,17 @@ void ParticleSystem::reset(Entity entity) {
}
}
+void ParticleSystem::setColorLut(Entity entity, const f32* rgba, i32 count) {
+ if (count != kColorLutSize || rgba == nullptr) {
+ colorLuts_.erase(entity); // 0 (or a mismatched bake) clears → fall back to start/end
+ return;
+ }
+ ColorLut& lut = colorLuts_[entity];
+ for (std::size_t i = 0; i < kColorLutSize; ++i) {
+ lut[i] = glm::vec4(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2], rgba[i * 4 + 3]);
+ }
+}
+
u32 ParticleSystem::aliveCount(Entity entity) const {
auto it = states_.find(entity);
if (it != states_.end()) {
@@ -216,8 +229,18 @@ void ParticleSystem::emitParticles(const ecs::ParticleEmitter& emitter,
}
}
+// Sample a baked color-over-life LUT at t∈[0,1] with linear interpolation between
+// the two nearest entries — the editor authors a gradient, TS bakes it to this.
+static glm::vec4 sampleColorLut(const ColorLut& lut, f32 t) {
+ f32 f = std::clamp(t, 0.0f, 1.0f) * static_cast<f32>(kColorLutSize - 1);
+ auto i = static_cast<std::size_t>(f);
+ std::size_t j = std::min(i + 1, static_cast<std::size_t>(kColorLutSize - 1));
+ return math::lerp(lut[i], lut[j], f - static_cast<f32>(i));
+}
+
void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
- EmitterState& state, f32 dt) {
+ EmitterState& state, f32 dt,
+ const ColorLut* colorLut) {
auto sizeEasing = static_cast<EasingType>(emitter.sizeEasing);
auto colorEasing = static_cast<EasingType>(emitter.colorEasing);
i32 totalFrames = emitter.spriteColumns * emitter.spriteRows;
@@ -246,8 +269,12 @@ void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
f32 sizeT = applyEasing(sizeEasing, t);
p.size = math::lerp(p.start_size, p.end_size, sizeT);
- f32 colorT = applyEasing(colorEasing, t);
- p.color = math::lerp(p.start_color, p.end_color, colorT);
+ if (colorLut) {
+ p.color = sampleColorLut(*colorLut, t);
+ } else {
+ f32 colorT = applyEasing(colorEasing, t);
+ p.color = math::lerp(p.start_color, p.end_color, colorT);
+ }
if (totalFrames > 1 && emitter.spriteFPS > 0.0f) {
f32 frameDuration = 1.0f / emitter.spriteFPS;
diff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hpp
index 9a9341510..9577ff937 100644
--- a/src/esengine/particle/ParticleSystem.hpp
+++ b/src/esengine/particle/ParticleSystem.hpp
@@ -13,9 +13,15 @@
#include <unordered_map>
#include <functional>
#include <random>
+#include <array>
namespace esengine::particle {
+// Resolution of the per-emitter color-over-life lookup table (baked in TS from a
+// gradient, sampled here per particle). 32 keeps gradients smooth and small.
+inline constexpr int kColorLutSize = 32;
+using ColorLut = std::array<glm::vec4, kColorLutSize>;
+
struct EmitterState {
ParticlePool pool;
f32 emission_accumulator = 0.0f;
@@ -45,17 +51,23 @@ public:
EmitterState* getState(Entity entity);
const EmitterState* getState(Entity entity) const;
+ /** Set (count == kColorLutSize) or clear (count == 0) an entity's color-over-life
+ * LUT. When set, particle color is sampled from it instead of start/end+easing. */
+ void setColorLut(Entity entity, const f32* rgba, i32 count);
+
private:
void emitParticles(const ecs::ParticleEmitter& emitter,
const ecs::Transform& transform,
EmitterState& state, u32 count);
- void updateParticles(const ecs::ParticleEmitter& emitter, EmitterState& state, f32 dt);
+ void updateParticles(const ecs::ParticleEmitter& emitter, EmitterState& state, f32 dt,
+ const ColorLut* colorLut);
f32 randomRange(f32 min, f32 max);
glm::vec2 randomDirection(f32 angleMin, f32 angleMax);
glm::vec2 randomShapeOffset(const ecs::ParticleEmitter& emitter);
std::unordered_map<Entity, EmitterState> states_;
+ std::unordered_map<Entity, ColorLut> colorLuts_;
std::mt19937 rng_;
std::vector<u32> dead_particle_indices_;
// RAII: auto-unregisters from the registry's onDestroy when this system is