@flare-engine/particles 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,6 +29,76 @@ const emitter = new ParticleEmitter({
29
29
  emitter.update(1 / 60);
30
30
  ```
31
31
 
32
+ ## Emitter shapes
33
+
34
+ By default every particle spawns at the emitter's `x`/`y`. A `shape` samples a spawn offset
35
+ instead — `point` (the default), `circle`, `ring`, `rect`, or `cone`:
36
+
37
+ ```ts
38
+ import { ParticleEmitter } from '@flare-engine/particles';
39
+
40
+ // An explosion: spawn on a ring, travel outward from the centre.
41
+ const blast = new ParticleEmitter({
42
+ rate: 0, lifetime: 0.6,
43
+ speed: 120, speedMax: 200,
44
+ direction: 0, spread: 0.15,
45
+ shape: { kind: 'ring', radius: 24, radial: true },
46
+ });
47
+ blast.x = 160;
48
+ blast.y = 120;
49
+ blast.burst(48);
50
+ ```
51
+
52
+ **Shape controls position; `direction` and `spread` still control velocity.** They compose rather
53
+ than compete. A shape with a meaningful outward normal — `circle`, `ring`, `cone` — can hand
54
+ velocity over to it with `radial: true`, which is what separates a ring of drifting particles from
55
+ an explosion. Without it, a ring spawns on the ring and everything still flies along `direction`.
56
+
57
+ | Shape | Position | Notes |
58
+ | --- | --- | --- |
59
+ | `{ kind: 'point' }` | the emitter origin | Default. Draws no random values, so an emitter without a shape produces the identical sequence to one before shapes existed. |
60
+ | `{ kind: 'circle', radius, radial? }` | uniform inside the disc | Uniform **by area** — the radial term is `sqrt`-weighted, so particles do not bunch at the centre. |
61
+ | `{ kind: 'ring', radius, thickness?, radial? }` | on the ring, `thickness` wide | `thickness` defaults to 0 (a bare ring), spread uniformly across the band. |
62
+ | `{ kind: 'rect', width, height }` | uniform in the rect | Centred on the emitter, not anchored at a corner. No outward normal, so `radial` does not apply. |
63
+ | `{ kind: 'cone', radius, angle }` | uniform in a wedge of half-angle `angle` | Oriented along `direction`. A wedge of *spawn points* — distinct from `spread`, which fans velocity out of a single point. |
64
+
65
+ `sampleEmitterShape(shape, rand, out, direction?)` is exported if you want to place something other
66
+ than particles. It writes into a caller-owned `ShapeSample` (`createShapeSample()`) and allocates
67
+ nothing, so it is safe per-particle in a steady-state loop. Every shape draws a fixed number of
68
+ values from `rand`, which is what keeps a seeded emitter replaying exactly.
69
+
70
+ ## Drawing into a sprite batch
71
+
72
+ `drawParticles` queues every live particle into a batch you own, so particles flush together with
73
+ the rest of the scene rather than forcing a second pass:
74
+
75
+ ```ts
76
+ import { drawParticles, ParticleEmitter } from '@flare-engine/particles';
77
+ import type { ParticleBatchLike, ParticleFrameLike } from '@flare-engine/particles';
78
+
79
+ declare const emitter: ParticleEmitter;
80
+ declare const batch: ParticleBatchLike; // a @flare-engine/render SpriteBatch satisfies this
81
+ declare const atlasImage: unknown;
82
+ declare const frame: ParticleFrameLike; // e.g. a SpriteFrame from @flare-engine/assets
83
+
84
+ // each frame, before the batch flushes
85
+ drawParticles(emitter.pool, batch, atlasImage, frame);
86
+ ```
87
+
88
+ The batch and frame are typed **structurally**, so this package still depends on nothing but
89
+ `@flare-engine/core` and `@flare-engine/math` and stays usable with no renderer. A real
90
+ `SpriteBatch` satisfies `ParticleBatchLike` — asserted by a runtime test in `@flare-engine/engine`,
91
+ not merely assumed.
92
+
93
+ The loop allocates nothing per particle, and skips any particle whose interpolated size or alpha has
94
+ reached zero rather than paying for an invisible draw call.
95
+
96
+ **Colour is not applied per particle.** The pool interpolates `startR/G/B → endR/G/B`, but a batch
97
+ retains an effect *reference* until it flushes, so a single reusable effect object would give every
98
+ particle the last one's colour — and one object per particle per frame is exactly the allocation this
99
+ package exists to avoid. Alpha *is* applied, because `drawRaw` takes it as a number. If you need
100
+ per-particle colour today, write the loop yourself over `pool.particles` and accept the cost.
101
+
32
102
  See [API spec](https://github.com/grzott/flare-engine/blob/main/docs/design/api-specs.md#flare-engineparticles--4kb-gzip).
33
103
 
34
104
  ## License
package/dist/index.d.mts CHANGED
@@ -79,6 +79,167 @@ declare class ParticlePool {
79
79
  clear(): void;
80
80
  }
81
81
  //#endregion
82
+ //#region src/draw-particles.d.ts
83
+ /**
84
+ * The frame rectangle within a texture. Structural on purpose: it matches
85
+ * `SpriteFrame` from `@flare-engine/assets` without this package depending on
86
+ * it — extra members like `name` are simply ignored.
87
+ */
88
+ interface ParticleFrameLike {
89
+ x: number;
90
+ y: number;
91
+ w: number;
92
+ h: number;
93
+ }
94
+ /**
95
+ * The one method this adapter needs from a sprite batch.
96
+ *
97
+ * Declared structurally so `@flare-engine/particles` keeps its two dependencies
98
+ * (`core`, `math`) and stays usable with no renderer at all. A real
99
+ * `SpriteBatch` from `@flare-engine/render` satisfies it; so does a test double.
100
+ * The parameter list mirrors `SpriteBatch.drawRaw`.
101
+ */
102
+ interface ParticleBatchLike {
103
+ drawRaw(image: unknown, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number, effect?: unknown, anchorX?: number, anchorY?: number, alpha?: number, rotation?: number, stretch?: boolean): void;
104
+ }
105
+ /** Options for `drawParticles`. */
106
+ interface DrawParticlesOptions {
107
+ /**
108
+ * A single effect applied to every particle in this call.
109
+ *
110
+ * Constant for the whole batch, and deliberately not per-particle: a batch
111
+ * retains the effect *reference* until it flushes, so one mutable object
112
+ * reused across the loop would give every particle the last particle's
113
+ * values. Per-particle effects therefore cost one object per particle per
114
+ * frame, which is exactly what this package exists to avoid — pass a constant
115
+ * here, or build the loop yourself over `pool.particles`.
116
+ */
117
+ effect?: unknown;
118
+ /** Anchor within the destination rect. Defaults to the centre (0.5, 0.5). */
119
+ anchorX?: number;
120
+ anchorY?: number;
121
+ }
122
+ /**
123
+ * Queue every live particle into a caller-owned sprite batch.
124
+ *
125
+ * Zero-alloc: the loop reads the pool's active list directly, allocates nothing
126
+ * per particle, and hands each one to `drawRaw` — so a steady-state emitter adds
127
+ * no garbage. Size and alpha come from the pool's own interpolators, and
128
+ * rotation from the particle.
129
+ *
130
+ * The batch is passed in rather than owned so particles share one batch, and one
131
+ * flush, with the rest of the scene — the `drawInto` idiom used elsewhere in the
132
+ * engine.
133
+ *
134
+ * ```ts
135
+ * // once, outside the loop
136
+ * const frame = sheet.frames.find((f) => f.name === 'spark')!;
137
+ * // each frame, before the batch flushes
138
+ * drawParticles(emitter.pool, batch, atlas.image, frame);
139
+ * ```
140
+ *
141
+ * **Colour is not applied per particle.** The pool interpolates
142
+ * `startR/G/B → endR/G/B`, but delivering that to a batch needs one effect
143
+ * object per particle per frame (see `DrawParticlesOptions.effect`). Alpha *is*
144
+ * applied, because `drawRaw` takes it as a number. For per-particle colour today,
145
+ * write the loop yourself over `pool.particles` and accept the allocation.
146
+ *
147
+ * `image` and `frame` are separate parameters because they are separate
148
+ * everywhere else in the engine — a frame is a rectangle within a texture and
149
+ * does not carry the texture.
150
+ */
151
+ declare function drawParticles(pool: ParticlePool, batch: ParticleBatchLike, image: unknown, frame: ParticleFrameLike, options?: DrawParticlesOptions): void;
152
+ //#endregion
153
+ //#region src/emitter-shape.d.ts
154
+ /**
155
+ * Emitter shapes — where a particle starts, not where it goes.
156
+ *
157
+ * The split matters, because `EmitterConfig` already owns direction: `direction`
158
+ * plus `spread` describe the velocity cone. A shape samples a **position offset**
159
+ * from the emitter origin and reports the outward normal at that point, so the
160
+ * two compose instead of competing. A shape with a meaningful outward direction
161
+ * can opt velocity into it with `radial: true` — that is what turns a `ring`
162
+ * from a circle of drifting particles into an explosion.
163
+ */
164
+ /** A filled disc of radius `radius`, sampled uniformly by area. */
165
+ interface EmitterCircleShape {
166
+ kind: 'circle';
167
+ radius: number;
168
+ /** Emit outward from the centre instead of along `config.direction`. */
169
+ radial?: boolean;
170
+ }
171
+ /** An annulus at `radius`, `thickness` wide (default 0 — a bare ring). */
172
+ interface EmitterRingShape {
173
+ kind: 'ring';
174
+ radius: number;
175
+ thickness?: number;
176
+ /** Emit outward from the centre instead of along `config.direction`. */
177
+ radial?: boolean;
178
+ }
179
+ /** An axis-aligned rectangle centred on the emitter, sampled uniformly. */
180
+ interface EmitterRectShape {
181
+ kind: 'rect';
182
+ width: number;
183
+ height: number;
184
+ }
185
+ /**
186
+ * A sector (wedge) of radius `radius` and half-angle `angle`, centred on
187
+ * `config.direction` and sampled uniformly by area.
188
+ *
189
+ * This is a *position* wedge, which is what keeps it distinct from
190
+ * `config.spread`: `spread` fans the velocity out of a single point, `cone`
191
+ * spreads the spawn points themselves across the wedge.
192
+ */
193
+ interface EmitterConeShape {
194
+ kind: 'cone';
195
+ radius: number;
196
+ angle: number;
197
+ /** Emit outward from the apex instead of along `config.direction`. */
198
+ radial?: boolean;
199
+ }
200
+ /** The emitter origin — every particle starts at the same point. The default. */
201
+ interface EmitterPointShape {
202
+ kind: 'point';
203
+ }
204
+ /** Where newly emitted particles are placed, relative to the emitter. */
205
+ type EmitterShape = EmitterPointShape | EmitterCircleShape | EmitterRingShape | EmitterRectShape | EmitterConeShape;
206
+ /**
207
+ * A sampled spawn point: an offset from the emitter origin, plus the outward
208
+ * normal at that offset.
209
+ *
210
+ * `nx`/`ny` are unit length for the radial shapes. For `point` and `rect` there
211
+ * is no meaningful outward direction and both are 0 — a caller honouring
212
+ * `radial` must fall back to `config.direction`, which is what `hasRadialNormal`
213
+ * is for.
214
+ */
215
+ interface ShapeSample {
216
+ x: number;
217
+ y: number;
218
+ nx: number;
219
+ ny: number;
220
+ }
221
+ /** A fresh, zeroed sample. Allocate once outside the loop and reuse. */
222
+ declare function createShapeSample(): ShapeSample;
223
+ /**
224
+ * Does this shape produce a usable outward normal?
225
+ *
226
+ * True only when the shape is radial *and* opted in. Lets a caller decide
227
+ * between the normal and `config.direction` without inspecting the union.
228
+ */
229
+ declare function hasRadialNormal(shape: EmitterShape): boolean;
230
+ /**
231
+ * Sample a spawn offset into `out`. Zero-alloc: nothing is constructed here, so
232
+ * this is safe to call once per emitted particle in a steady-state loop.
233
+ *
234
+ * `rand` must return a float in [0, 1). Pass the emitter's seeded generator to
235
+ * keep emission deterministic — every shape draws a fixed number of values per
236
+ * call (`point` 0, `ring`/`rect` 2, `circle`/`cone` 2), so a given seed replays
237
+ * exactly.
238
+ *
239
+ * `direction` orients `cone` and is ignored by every other shape.
240
+ */
241
+ declare function sampleEmitterShape(shape: EmitterShape, rand: () => number, out: ShapeSample, direction?: number): ShapeSample;
242
+ //#endregion
82
243
  //#region src/particle-emitter.d.ts
83
244
  /** Configuration for a ParticleEmitter. */
84
245
  interface EmitterConfig {
@@ -114,6 +275,15 @@ interface EmitterConfig {
114
275
  angularVelocityMax?: number;
115
276
  /** Maximum active particles (used as pool capacity default when no opts.maxParticles given). */
116
277
  maxParticles?: number;
278
+ /**
279
+ * Where particles spawn, relative to the emitter position. Defaults to
280
+ * `{ kind: 'point' }`, which is the pre-existing behaviour — every particle
281
+ * starts exactly at `x`/`y`.
282
+ *
283
+ * A shape samples position only; `direction` and `spread` still govern
284
+ * velocity, unless the shape sets `radial: true` (see `EmitterShape`).
285
+ */
286
+ shape?: EmitterShape;
117
287
  }
118
288
  /** Construction options for ParticleEmitter. */
119
289
  interface EmitterOptions {
@@ -145,6 +315,10 @@ declare class ParticleEmitter {
145
315
  emitting: boolean;
146
316
  private _emitAccumulator;
147
317
  private _seed;
318
+ /** Reused spawn-offset buffer — one per emitter, never per particle. */
319
+ private readonly _sample;
320
+ /** Bound once at construction; binding per emit would allocate a closure. */
321
+ private readonly _rand;
148
322
  constructor(config: EmitterConfig, opts?: EmitterOptions);
149
323
  /** Reset the LCG seed — restarts the particle random sequence from this seed. */
150
324
  reseed(seed: number): void;
@@ -164,5 +338,5 @@ declare class ParticleEmitter {
164
338
  private _emitOne;
165
339
  }
166
340
  //#endregion
167
- export { type EmitterConfig, type EmitterOptions, type Particle, ParticleEmitter, ParticlePool };
341
+ export { type DrawParticlesOptions, type EmitterCircleShape, type EmitterConeShape, type EmitterConfig, type EmitterOptions, type EmitterPointShape, type EmitterRectShape, type EmitterRingShape, type EmitterShape, type Particle, type ParticleBatchLike, ParticleEmitter, type ParticleFrameLike, ParticlePool, type ShapeSample, createShapeSample, drawParticles, hasRadialNormal, sampleEmitterShape };
168
342
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/particle-pool.ts","../src/particle-emitter.ts"],"mappings":";;;UAIiB;;EAEf;EACA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;;;;;cAuDW;UACH;UACA;cAEI;;MAMR;;;;;;;MAUA;;MAKA,sBAAsB;;EAK1B,WAAW;;;;;EAWX,cAAc;;EASd,OAAO,YAAY,kBAAkB;;EA+BrC,QAAQ,GAAG;;EAMX,SAAS,GAAG;;UAMJ;;;;;;;EAQR,SAAS,GAAG,WAAW;;EAKvB,aAAa,GAAG,UAAU,KAAK,QAAQ;;EAUvC;;;;;UCvMe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;EACA;;EAEA,aAAa;;EAEb,WAAW;;EAEX;EACA;;EAEA;;;UAIe;;;;;;EAMf;;;;;EAKA;;;;;;;;cASW;WACF,QAAQ;WACR,MAAM;;EAGf;EACA;;EAGA;UAEQ;UACA;cAEI,QAAQ,eAAe,OAAO;;EAQ1C,OAAO;;UAKC;;EAQR,OAAO;;EAgBP,MAAM;;EAON;;UAOQ;;UAMA;;UAKA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/particle-pool.ts","../src/draw-particles.ts","../src/emitter-shape.ts","../src/particle-emitter.ts"],"mappings":";;;UAIiB;;EAEf;EACA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;;;;;cAuDW;UACH;UACA;cAEI;;MAMR;;;;;;;MAUA;;MAKA,sBAAsB;;EAK1B,WAAW;;;;;EAWX,cAAc;;EASd,OAAO,YAAY,kBAAkB;;EA+BrC,QAAQ,GAAG;;EAMX,SAAS,GAAG;;UAMJ;;;;;;;EAQR,SAAS,GAAG,WAAW;;EAKvB,aAAa,GAAG,UAAU,KAAK,QAAQ;;EAUvC;;;;;;;;;UCrMe;EACf;EACA;EACA;EACA;;;;;;;;;;UAWe;EACf,QACE,gBACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,kBACA,kBACA,kBACA,gBACA,mBACA;;;UAKa;;;;;;;;;;;EAWf;;EAEA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCc,cACd,MAAM,cACN,OAAO,mBACP,gBACA,OAAO,mBACP,UAAU;;;;;;;;;;;;;;UClFK;EACf;EACA;;EAEA;;;UAIe;EACf;EACA;EACA;;EAEA;;;UAIe;EACf;EACA;EACA;;;;;;;;;;UAWe;EACf;EACA;EACA;;EAEA;;;UAIe;EACf;;;KAIU,eACR,oBACA,qBACA,mBACA,mBACA;;;;;;;;;;UAWa;EACf;EACA;EACA;EACA;;;iBAIc,qBAAqB;;;;;;;iBAYrB,gBAAgB,OAAO;;;;;;;;;;;;iBAsBvB,mBACd,OAAO,cACP,oBACA,KAAK,aACL,qBACC;;;;UCjHc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;EACA;;EAEA,aAAa;;EAEb,WAAW;;EAEX;EACA;;EAEA;;;;;;;;;EASA,QAAQ;;;UAIO;;;;;;EAMf;;;;;EAKA;;;;;;;;cASW;WACF,QAAQ;WACR,MAAM;;EAGf;EACA;;EAGA;UAEQ;UACA;;mBAES;;mBAEA;cAEL,QAAQ,eAAe,OAAO;;EAQ1C,OAAO;;UAKC;;EAQR,OAAO;;EAgBP,MAAM;;EAON;;UAOQ;;UAMA;;UAKA"}
package/dist/index.d.ts CHANGED
@@ -79,6 +79,167 @@ declare class ParticlePool {
79
79
  clear(): void;
80
80
  }
81
81
  //#endregion
82
+ //#region src/draw-particles.d.ts
83
+ /**
84
+ * The frame rectangle within a texture. Structural on purpose: it matches
85
+ * `SpriteFrame` from `@flare-engine/assets` without this package depending on
86
+ * it — extra members like `name` are simply ignored.
87
+ */
88
+ interface ParticleFrameLike {
89
+ x: number;
90
+ y: number;
91
+ w: number;
92
+ h: number;
93
+ }
94
+ /**
95
+ * The one method this adapter needs from a sprite batch.
96
+ *
97
+ * Declared structurally so `@flare-engine/particles` keeps its two dependencies
98
+ * (`core`, `math`) and stays usable with no renderer at all. A real
99
+ * `SpriteBatch` from `@flare-engine/render` satisfies it; so does a test double.
100
+ * The parameter list mirrors `SpriteBatch.drawRaw`.
101
+ */
102
+ interface ParticleBatchLike {
103
+ drawRaw(image: unknown, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number, effect?: unknown, anchorX?: number, anchorY?: number, alpha?: number, rotation?: number, stretch?: boolean): void;
104
+ }
105
+ /** Options for `drawParticles`. */
106
+ interface DrawParticlesOptions {
107
+ /**
108
+ * A single effect applied to every particle in this call.
109
+ *
110
+ * Constant for the whole batch, and deliberately not per-particle: a batch
111
+ * retains the effect *reference* until it flushes, so one mutable object
112
+ * reused across the loop would give every particle the last particle's
113
+ * values. Per-particle effects therefore cost one object per particle per
114
+ * frame, which is exactly what this package exists to avoid — pass a constant
115
+ * here, or build the loop yourself over `pool.particles`.
116
+ */
117
+ effect?: unknown;
118
+ /** Anchor within the destination rect. Defaults to the centre (0.5, 0.5). */
119
+ anchorX?: number;
120
+ anchorY?: number;
121
+ }
122
+ /**
123
+ * Queue every live particle into a caller-owned sprite batch.
124
+ *
125
+ * Zero-alloc: the loop reads the pool's active list directly, allocates nothing
126
+ * per particle, and hands each one to `drawRaw` — so a steady-state emitter adds
127
+ * no garbage. Size and alpha come from the pool's own interpolators, and
128
+ * rotation from the particle.
129
+ *
130
+ * The batch is passed in rather than owned so particles share one batch, and one
131
+ * flush, with the rest of the scene — the `drawInto` idiom used elsewhere in the
132
+ * engine.
133
+ *
134
+ * ```ts
135
+ * // once, outside the loop
136
+ * const frame = sheet.frames.find((f) => f.name === 'spark')!;
137
+ * // each frame, before the batch flushes
138
+ * drawParticles(emitter.pool, batch, atlas.image, frame);
139
+ * ```
140
+ *
141
+ * **Colour is not applied per particle.** The pool interpolates
142
+ * `startR/G/B → endR/G/B`, but delivering that to a batch needs one effect
143
+ * object per particle per frame (see `DrawParticlesOptions.effect`). Alpha *is*
144
+ * applied, because `drawRaw` takes it as a number. For per-particle colour today,
145
+ * write the loop yourself over `pool.particles` and accept the allocation.
146
+ *
147
+ * `image` and `frame` are separate parameters because they are separate
148
+ * everywhere else in the engine — a frame is a rectangle within a texture and
149
+ * does not carry the texture.
150
+ */
151
+ declare function drawParticles(pool: ParticlePool, batch: ParticleBatchLike, image: unknown, frame: ParticleFrameLike, options?: DrawParticlesOptions): void;
152
+ //#endregion
153
+ //#region src/emitter-shape.d.ts
154
+ /**
155
+ * Emitter shapes — where a particle starts, not where it goes.
156
+ *
157
+ * The split matters, because `EmitterConfig` already owns direction: `direction`
158
+ * plus `spread` describe the velocity cone. A shape samples a **position offset**
159
+ * from the emitter origin and reports the outward normal at that point, so the
160
+ * two compose instead of competing. A shape with a meaningful outward direction
161
+ * can opt velocity into it with `radial: true` — that is what turns a `ring`
162
+ * from a circle of drifting particles into an explosion.
163
+ */
164
+ /** A filled disc of radius `radius`, sampled uniformly by area. */
165
+ interface EmitterCircleShape {
166
+ kind: 'circle';
167
+ radius: number;
168
+ /** Emit outward from the centre instead of along `config.direction`. */
169
+ radial?: boolean;
170
+ }
171
+ /** An annulus at `radius`, `thickness` wide (default 0 — a bare ring). */
172
+ interface EmitterRingShape {
173
+ kind: 'ring';
174
+ radius: number;
175
+ thickness?: number;
176
+ /** Emit outward from the centre instead of along `config.direction`. */
177
+ radial?: boolean;
178
+ }
179
+ /** An axis-aligned rectangle centred on the emitter, sampled uniformly. */
180
+ interface EmitterRectShape {
181
+ kind: 'rect';
182
+ width: number;
183
+ height: number;
184
+ }
185
+ /**
186
+ * A sector (wedge) of radius `radius` and half-angle `angle`, centred on
187
+ * `config.direction` and sampled uniformly by area.
188
+ *
189
+ * This is a *position* wedge, which is what keeps it distinct from
190
+ * `config.spread`: `spread` fans the velocity out of a single point, `cone`
191
+ * spreads the spawn points themselves across the wedge.
192
+ */
193
+ interface EmitterConeShape {
194
+ kind: 'cone';
195
+ radius: number;
196
+ angle: number;
197
+ /** Emit outward from the apex instead of along `config.direction`. */
198
+ radial?: boolean;
199
+ }
200
+ /** The emitter origin — every particle starts at the same point. The default. */
201
+ interface EmitterPointShape {
202
+ kind: 'point';
203
+ }
204
+ /** Where newly emitted particles are placed, relative to the emitter. */
205
+ type EmitterShape = EmitterPointShape | EmitterCircleShape | EmitterRingShape | EmitterRectShape | EmitterConeShape;
206
+ /**
207
+ * A sampled spawn point: an offset from the emitter origin, plus the outward
208
+ * normal at that offset.
209
+ *
210
+ * `nx`/`ny` are unit length for the radial shapes. For `point` and `rect` there
211
+ * is no meaningful outward direction and both are 0 — a caller honouring
212
+ * `radial` must fall back to `config.direction`, which is what `hasRadialNormal`
213
+ * is for.
214
+ */
215
+ interface ShapeSample {
216
+ x: number;
217
+ y: number;
218
+ nx: number;
219
+ ny: number;
220
+ }
221
+ /** A fresh, zeroed sample. Allocate once outside the loop and reuse. */
222
+ declare function createShapeSample(): ShapeSample;
223
+ /**
224
+ * Does this shape produce a usable outward normal?
225
+ *
226
+ * True only when the shape is radial *and* opted in. Lets a caller decide
227
+ * between the normal and `config.direction` without inspecting the union.
228
+ */
229
+ declare function hasRadialNormal(shape: EmitterShape): boolean;
230
+ /**
231
+ * Sample a spawn offset into `out`. Zero-alloc: nothing is constructed here, so
232
+ * this is safe to call once per emitted particle in a steady-state loop.
233
+ *
234
+ * `rand` must return a float in [0, 1). Pass the emitter's seeded generator to
235
+ * keep emission deterministic — every shape draws a fixed number of values per
236
+ * call (`point` 0, `ring`/`rect` 2, `circle`/`cone` 2), so a given seed replays
237
+ * exactly.
238
+ *
239
+ * `direction` orients `cone` and is ignored by every other shape.
240
+ */
241
+ declare function sampleEmitterShape(shape: EmitterShape, rand: () => number, out: ShapeSample, direction?: number): ShapeSample;
242
+ //#endregion
82
243
  //#region src/particle-emitter.d.ts
83
244
  /** Configuration for a ParticleEmitter. */
84
245
  interface EmitterConfig {
@@ -114,6 +275,15 @@ interface EmitterConfig {
114
275
  angularVelocityMax?: number;
115
276
  /** Maximum active particles (used as pool capacity default when no opts.maxParticles given). */
116
277
  maxParticles?: number;
278
+ /**
279
+ * Where particles spawn, relative to the emitter position. Defaults to
280
+ * `{ kind: 'point' }`, which is the pre-existing behaviour — every particle
281
+ * starts exactly at `x`/`y`.
282
+ *
283
+ * A shape samples position only; `direction` and `spread` still govern
284
+ * velocity, unless the shape sets `radial: true` (see `EmitterShape`).
285
+ */
286
+ shape?: EmitterShape;
117
287
  }
118
288
  /** Construction options for ParticleEmitter. */
119
289
  interface EmitterOptions {
@@ -145,6 +315,10 @@ declare class ParticleEmitter {
145
315
  emitting: boolean;
146
316
  private _emitAccumulator;
147
317
  private _seed;
318
+ /** Reused spawn-offset buffer — one per emitter, never per particle. */
319
+ private readonly _sample;
320
+ /** Bound once at construction; binding per emit would allocate a closure. */
321
+ private readonly _rand;
148
322
  constructor(config: EmitterConfig, opts?: EmitterOptions);
149
323
  /** Reset the LCG seed — restarts the particle random sequence from this seed. */
150
324
  reseed(seed: number): void;
@@ -164,5 +338,5 @@ declare class ParticleEmitter {
164
338
  private _emitOne;
165
339
  }
166
340
  //#endregion
167
- export { type EmitterConfig, type EmitterOptions, type Particle, ParticleEmitter, ParticlePool };
341
+ export { type DrawParticlesOptions, type EmitterCircleShape, type EmitterConeShape, type EmitterConfig, type EmitterOptions, type EmitterPointShape, type EmitterRectShape, type EmitterRingShape, type EmitterShape, type Particle, type ParticleBatchLike, ParticleEmitter, type ParticleFrameLike, ParticlePool, type ShapeSample, createShapeSample, drawParticles, hasRadialNormal, sampleEmitterShape };
168
342
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/particle-pool.ts","../src/particle-emitter.ts"],"mappings":";;;UAIiB;;EAEf;EACA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;;;;;cAuDW;UACH;UACA;cAEI;;MAMR;;;;;;;MAUA;;MAKA,sBAAsB;;EAK1B,WAAW;;;;;EAWX,cAAc;;EASd,OAAO,YAAY,kBAAkB;;EA+BrC,QAAQ,GAAG;;EAMX,SAAS,GAAG;;UAMJ;;;;;;;EAQR,SAAS,GAAG,WAAW;;EAKvB,aAAa,GAAG,UAAU,KAAK,QAAQ;;EAUvC;;;;;UCvMe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;EACA;;EAEA,aAAa;;EAEb,WAAW;;EAEX;EACA;;EAEA;;;UAIe;;;;;;EAMf;;;;;EAKA;;;;;;;;cASW;WACF,QAAQ;WACR,MAAM;;EAGf;EACA;;EAGA;UAEQ;UACA;cAEI,QAAQ,eAAe,OAAO;;EAQ1C,OAAO;;UAKC;;EAQR,OAAO;;EAgBP,MAAM;;EAON;;UAOQ;;UAMA;;UAKA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/particle-pool.ts","../src/draw-particles.ts","../src/emitter-shape.ts","../src/particle-emitter.ts"],"mappings":";;;UAIiB;;EAEf;EACA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;;;;;cAuDW;UACH;UACA;cAEI;;MAMR;;;;;;;MAUA;;MAKA,sBAAsB;;EAK1B,WAAW;;;;;EAWX,cAAc;;EASd,OAAO,YAAY,kBAAkB;;EA+BrC,QAAQ,GAAG;;EAMX,SAAS,GAAG;;UAMJ;;;;;;;EAQR,SAAS,GAAG,WAAW;;EAKvB,aAAa,GAAG,UAAU,KAAK,QAAQ;;EAUvC;;;;;;;;;UCrMe;EACf;EACA;EACA;EACA;;;;;;;;;;UAWe;EACf,QACE,gBACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,kBACA,kBACA,kBACA,gBACA,mBACA;;;UAKa;;;;;;;;;;;EAWf;;EAEA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCc,cACd,MAAM,cACN,OAAO,mBACP,gBACA,OAAO,mBACP,UAAU;;;;;;;;;;;;;;UClFK;EACf;EACA;;EAEA;;;UAIe;EACf;EACA;EACA;;EAEA;;;UAIe;EACf;EACA;EACA;;;;;;;;;;UAWe;EACf;EACA;EACA;;EAEA;;;UAIe;EACf;;;KAIU,eACR,oBACA,qBACA,mBACA,mBACA;;;;;;;;;;UAWa;EACf;EACA;EACA;EACA;;;iBAIc,qBAAqB;;;;;;;iBAYrB,gBAAgB,OAAO;;;;;;;;;;;;iBAsBvB,mBACd,OAAO,cACP,oBACA,KAAK,aACL,qBACC;;;;UCjHc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;EACA;;EAEA,aAAa;;EAEb,WAAW;;EAEX;EACA;;EAEA;;;;;;;;;EASA,QAAQ;;;UAIO;;;;;;EAMf;;;;;EAKA;;;;;;;;cASW;WACF,QAAQ;WACR,MAAM;;EAGf;EACA;;EAGA;UAEQ;UACA;;mBAES;;mBAEA;cAEL,QAAQ,eAAe,OAAO;;EAQ1C,OAAO;;UAKC;;EAQR,OAAO;;EAgBP,MAAM;;EAON;;UAOQ;;UAMA;;UAKA"}
package/dist/index.js CHANGED
@@ -1,5 +1,147 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _flare_engine_core = require("@flare-engine/core");
3
+ //#region src/draw-particles.ts
4
+ /**
5
+ * Queue every live particle into a caller-owned sprite batch.
6
+ *
7
+ * Zero-alloc: the loop reads the pool's active list directly, allocates nothing
8
+ * per particle, and hands each one to `drawRaw` — so a steady-state emitter adds
9
+ * no garbage. Size and alpha come from the pool's own interpolators, and
10
+ * rotation from the particle.
11
+ *
12
+ * The batch is passed in rather than owned so particles share one batch, and one
13
+ * flush, with the rest of the scene — the `drawInto` idiom used elsewhere in the
14
+ * engine.
15
+ *
16
+ * ```ts
17
+ * // once, outside the loop
18
+ * const frame = sheet.frames.find((f) => f.name === 'spark')!;
19
+ * // each frame, before the batch flushes
20
+ * drawParticles(emitter.pool, batch, atlas.image, frame);
21
+ * ```
22
+ *
23
+ * **Colour is not applied per particle.** The pool interpolates
24
+ * `startR/G/B → endR/G/B`, but delivering that to a batch needs one effect
25
+ * object per particle per frame (see `DrawParticlesOptions.effect`). Alpha *is*
26
+ * applied, because `drawRaw` takes it as a number. For per-particle colour today,
27
+ * write the loop yourself over `pool.particles` and accept the allocation.
28
+ *
29
+ * `image` and `frame` are separate parameters because they are separate
30
+ * everywhere else in the engine — a frame is a rectangle within a texture and
31
+ * does not carry the texture.
32
+ */
33
+ function drawParticles(pool, batch, image, frame, options) {
34
+ const particles = pool.particles;
35
+ const count = particles.length;
36
+ if (count === 0) return;
37
+ const effect = options?.effect;
38
+ const anchorX = options?.anchorX ?? .5;
39
+ const anchorY = options?.anchorY ?? .5;
40
+ const srcX = frame.x;
41
+ const srcY = frame.y;
42
+ const srcW = frame.w;
43
+ const srcH = frame.h;
44
+ for (let i = 0; i < count; i++) {
45
+ const p = particles[i];
46
+ const size = pool.getSize(p);
47
+ if (size <= 0) continue;
48
+ const alpha = pool.getAlpha(p);
49
+ if (alpha <= 0) continue;
50
+ batch.drawRaw(image, srcX, srcY, srcW, srcH, p.x, p.y, size, size, effect, anchorX, anchorY, alpha, p.rotation);
51
+ }
52
+ }
53
+ //#endregion
54
+ //#region src/emitter-shape.ts
55
+ /** A fresh, zeroed sample. Allocate once outside the loop and reuse. */
56
+ function createShapeSample() {
57
+ return {
58
+ x: 0,
59
+ y: 0,
60
+ nx: 0,
61
+ ny: 0
62
+ };
63
+ }
64
+ const TAU = Math.PI * 2;
65
+ /**
66
+ * Does this shape produce a usable outward normal?
67
+ *
68
+ * True only when the shape is radial *and* opted in. Lets a caller decide
69
+ * between the normal and `config.direction` without inspecting the union.
70
+ */
71
+ function hasRadialNormal(shape) {
72
+ switch (shape.kind) {
73
+ case "circle":
74
+ case "ring":
75
+ case "cone": return shape.radial === true;
76
+ default: return false;
77
+ }
78
+ }
79
+ /**
80
+ * Sample a spawn offset into `out`. Zero-alloc: nothing is constructed here, so
81
+ * this is safe to call once per emitted particle in a steady-state loop.
82
+ *
83
+ * `rand` must return a float in [0, 1). Pass the emitter's seeded generator to
84
+ * keep emission deterministic — every shape draws a fixed number of values per
85
+ * call (`point` 0, `ring`/`rect` 2, `circle`/`cone` 2), so a given seed replays
86
+ * exactly.
87
+ *
88
+ * `direction` orients `cone` and is ignored by every other shape.
89
+ */
90
+ function sampleEmitterShape(shape, rand, out, direction = 0) {
91
+ switch (shape.kind) {
92
+ case "point":
93
+ out.x = 0;
94
+ out.y = 0;
95
+ out.nx = 0;
96
+ out.ny = 0;
97
+ return out;
98
+ case "circle": {
99
+ const angle = rand() * TAU;
100
+ const r = Math.sqrt(rand()) * Math.max(0, shape.radius);
101
+ const cos = Math.cos(angle);
102
+ const sin = Math.sin(angle);
103
+ out.x = cos * r;
104
+ out.y = sin * r;
105
+ out.nx = cos;
106
+ out.ny = sin;
107
+ return out;
108
+ }
109
+ case "ring": {
110
+ const angle = rand() * TAU;
111
+ const thickness = Math.max(0, shape.thickness ?? 0);
112
+ const r = Math.max(0, shape.radius) + (rand() - .5) * thickness;
113
+ const cos = Math.cos(angle);
114
+ const sin = Math.sin(angle);
115
+ out.x = cos * r;
116
+ out.y = sin * r;
117
+ out.nx = cos;
118
+ out.ny = sin;
119
+ return out;
120
+ }
121
+ case "rect": {
122
+ const w = Math.max(0, shape.width);
123
+ const h = Math.max(0, shape.height);
124
+ out.x = (rand() - .5) * w;
125
+ out.y = (rand() - .5) * h;
126
+ out.nx = 0;
127
+ out.ny = 0;
128
+ return out;
129
+ }
130
+ case "cone": {
131
+ const half = Math.max(0, shape.angle);
132
+ const angle = direction + (rand() * 2 - 1) * half;
133
+ const r = Math.sqrt(rand()) * Math.max(0, shape.radius);
134
+ const cos = Math.cos(angle);
135
+ const sin = Math.sin(angle);
136
+ out.x = cos * r;
137
+ out.y = sin * r;
138
+ out.nx = cos;
139
+ out.ny = sin;
140
+ return out;
141
+ }
142
+ }
143
+ }
144
+ //#endregion
3
145
  //#region src/particle-pool.ts
4
146
  /** Create a default (inactive) particle. */
5
147
  function createParticle() {
@@ -176,6 +318,10 @@ var ParticleEmitter = class {
176
318
  emitting = true;
177
319
  _emitAccumulator = 0;
178
320
  _seed = 0;
321
+ /** Reused spawn-offset buffer — one per emitter, never per particle. */
322
+ _sample = createShapeSample();
323
+ /** Bound once at construction; binding per emit would allocate a closure. */
324
+ _rand = () => this._random();
179
325
  constructor(config, opts) {
180
326
  this.config = config;
181
327
  const cap = opts?.maxParticles ?? config.maxParticles ?? 256;
@@ -231,12 +377,23 @@ var ParticleEmitter = class {
231
377
  const p = this.pool.tryAcquire();
232
378
  if (!p) return false;
233
379
  const c = this.config;
234
- p.x = this.x;
235
- p.y = this.y;
236
- const angle = c.direction + this._randomRange(-c.spread, c.spread);
237
- const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;
238
- p.vx = Math.cos(angle) * speed;
239
- p.vy = Math.sin(angle) * speed;
380
+ const shape = c.shape;
381
+ if (shape === void 0 || shape.kind === "point") {
382
+ p.x = this.x;
383
+ p.y = this.y;
384
+ const angle = c.direction + this._randomRange(-c.spread, c.spread);
385
+ const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;
386
+ p.vx = Math.cos(angle) * speed;
387
+ p.vy = Math.sin(angle) * speed;
388
+ } else {
389
+ const s = sampleEmitterShape(shape, this._rand, this._sample, c.direction);
390
+ p.x = this.x + s.x;
391
+ p.y = this.y + s.y;
392
+ const angle = (hasRadialNormal(shape) ? Math.atan2(s.ny, s.nx) : c.direction) + this._randomRange(-c.spread, c.spread);
393
+ const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;
394
+ p.vx = Math.cos(angle) * speed;
395
+ p.vy = Math.sin(angle) * speed;
396
+ }
240
397
  const lifetime = c.lifetimeMax ? this._randomRange(c.lifetime, c.lifetimeMax) : c.lifetime;
241
398
  p.life = lifetime;
242
399
  p.maxLife = lifetime;
@@ -261,5 +418,9 @@ var ParticleEmitter = class {
261
418
  //#endregion
262
419
  exports.ParticleEmitter = ParticleEmitter;
263
420
  exports.ParticlePool = ParticlePool;
421
+ exports.createShapeSample = createShapeSample;
422
+ exports.drawParticles = drawParticles;
423
+ exports.hasRadialNormal = hasRadialNormal;
424
+ exports.sampleEmitterShape = sampleEmitterShape;
264
425
 
265
426
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Pool"],"sources":["../src/particle-pool.ts","../src/particle-emitter.ts"],"sourcesContent":["import { Pool } from '@flare-engine/core';\nimport type { Color } from '@flare-engine/math';\n\n/** A single particle. Managed by ParticlePool — not user-facing. */\nexport interface Particle {\n /** World position. */\n x: number;\n y: number;\n /** Velocity in pixels/second. */\n vx: number;\n vy: number;\n /** Time remaining in seconds. */\n life: number;\n /** Total lifetime for interpolation. */\n maxLife: number;\n /** Start/end size for interpolation. */\n startSize: number;\n endSize: number;\n /** Start/end alpha for interpolation. */\n startAlpha: number;\n endAlpha: number;\n /** Start/end color components for interpolation. */\n startR: number;\n startG: number;\n startB: number;\n endR: number;\n endG: number;\n endB: number;\n /** Rotation in radians. */\n rotation: number;\n /** Angular velocity in radians/second. */\n angularVelocity: number;\n /** Whether this particle is active. */\n active: boolean;\n}\n\n/** Create a default (inactive) particle. */\nfunction createParticle(): Particle {\n return {\n x: 0,\n y: 0,\n vx: 0,\n vy: 0,\n life: 0,\n maxLife: 0,\n startSize: 1,\n endSize: 1,\n startAlpha: 1,\n endAlpha: 0,\n startR: 1,\n startG: 1,\n startB: 1,\n endR: 1,\n endG: 1,\n endB: 1,\n rotation: 0,\n angularVelocity: 0,\n active: false,\n };\n}\n\n/** Reset a particle to default (inactive) state. */\nfunction resetParticle(p: Particle): void {\n p.x = 0;\n p.y = 0;\n p.vx = 0;\n p.vy = 0;\n p.life = 0;\n p.maxLife = 0;\n p.startSize = 1;\n p.endSize = 1;\n p.startAlpha = 1;\n p.endAlpha = 0;\n p.startR = 1;\n p.startG = 1;\n p.startB = 1;\n p.endR = 1;\n p.endG = 1;\n p.endB = 1;\n p.rotation = 0;\n p.angularVelocity = 0;\n p.active = false;\n}\n\n/**\n * ParticlePool — pre-allocated pool of particles.\n * Zero GC pressure during steady-state gameplay.\n */\nexport class ParticlePool {\n private _pool: Pool<Particle>;\n private _active: Particle[] = [];\n\n constructor(capacity = 256) {\n this._pool = new Pool(createParticle, resetParticle, { capacity });\n this._pool.prewarm(capacity);\n }\n\n /** Number of currently active particles. */\n get activeCount(): number {\n return this._active.length;\n }\n\n /**\n * Cumulative factory calls made by the internal pool's acquire()/tryAcquire().\n * prewarm() is excluded: factory calls there pre-fill the free list and are\n * not counted. Intended use: snapshot before and after a frame — a non-zero\n * delta in steady state means unexpected allocation.\n */\n get created(): number {\n return this._pool.created;\n }\n\n /** Read-only access to active particles. */\n get particles(): readonly Particle[] {\n return this._active;\n }\n\n /** Acquire a particle from the pool. */\n acquire(): Particle {\n const p = this._pool.acquire();\n p.active = true;\n this._active.push(p);\n return p;\n }\n\n /**\n * Acquire a particle only if the pool is below capacity.\n * Returns null at cap — no allocation occurs.\n */\n tryAcquire(): Particle | null {\n const p = this._pool.tryAcquire();\n if (!p) return null;\n p.active = true;\n this._active.push(p);\n return p;\n }\n\n /** Update all active particles. Releases dead particles. */\n update(dt: number, gravityX: number, gravityY: number): void {\n let i = 0;\n while (i < this._active.length) {\n const p = this._active[i]!;\n p.life -= dt;\n\n if (p.life <= 0) {\n // Dead — release and swap-remove\n p.active = false;\n this._pool.release(p);\n this._active[i] = this._active[this._active.length - 1]!;\n this._active.pop();\n continue;\n }\n\n // Apply gravity\n p.vx += gravityX * dt;\n p.vy += gravityY * dt;\n\n // Integrate position\n p.x += p.vx * dt;\n p.y += p.vy * dt;\n\n // Rotate\n p.rotation += p.angularVelocity * dt;\n\n i++;\n }\n }\n\n /** Get interpolated size for a particle (0 = start, 1 = end of life). */\n getSize(p: Particle): number {\n const t = 1 - p.life / p.maxLife;\n return p.startSize + (p.endSize - p.startSize) * t;\n }\n\n /** Get interpolated alpha for a particle. */\n getAlpha(p: Particle): number {\n const t = 1 - p.life / p.maxLife;\n return p.startAlpha + (p.endAlpha - p.startAlpha) * t;\n }\n\n /** Shared color buffer — avoids per-call allocation in the render hot path. */\n private _colorBuf: Color = { r: 1, g: 1, b: 1, a: 1 };\n\n /**\n * Get interpolated color for a particle.\n *\n * Returns a shared buffer — read the values immediately, do not retain the\n * reference. For a fresh object call `getColorInto()` with your own out param.\n */\n getColor(p: Particle): Color {\n return this.getColorInto(p, this._colorBuf);\n }\n\n /** Zero-alloc variant — writes the interpolated color into `out`. */\n getColorInto(p: Particle, out: Color): Color {\n const t = 1 - p.life / p.maxLife;\n out.r = p.startR + (p.endR - p.startR) * t;\n out.g = p.startG + (p.endG - p.startG) * t;\n out.b = p.startB + (p.endB - p.startB) * t;\n out.a = p.startAlpha + (p.endAlpha - p.startAlpha) * t;\n return out;\n }\n\n /** Release all active particles back to pool. */\n clear(): void {\n for (const p of this._active) {\n p.active = false;\n this._pool.release(p);\n }\n this._active.length = 0;\n }\n}\n","import type { Color } from '@flare-engine/math';\nimport type { Particle } from './particle-pool.js';\nimport { ParticlePool } from './particle-pool.js';\n\n/** Configuration for a ParticleEmitter. */\nexport interface EmitterConfig {\n /** Emission rate in particles per second. */\n rate: number;\n /** Particle lifetime in seconds. */\n lifetime: number;\n /** Min lifetime (if set, actual lifetime is random between lifetime and lifetimeMax). */\n lifetimeMax?: number;\n /** Initial speed in pixels/second. */\n speed: number;\n /** Max speed (random range). */\n speedMax?: number;\n /** Emission direction in radians (0 = right). */\n direction: number;\n /** Spread angle in radians (half-angle of the emission cone). */\n spread: number;\n /** Gravity in pixels/second² (applied each frame). */\n gravityX?: number;\n gravityY?: number;\n /** Start size and end size. */\n startSize?: number;\n endSize?: number;\n /** Start alpha and end alpha. */\n startAlpha?: number;\n endAlpha?: number;\n /** Start color. */\n startColor?: Color;\n /** End color. */\n endColor?: Color;\n /** Angular velocity range (radians/second). */\n angularVelocity?: number;\n angularVelocityMax?: number;\n /** Maximum active particles (used as pool capacity default when no opts.maxParticles given). */\n maxParticles?: number;\n}\n\n/** Construction options for ParticleEmitter. */\nexport interface EmitterOptions {\n /**\n * Hard cap on simultaneously active particles.\n * Overrides config.maxParticles when provided.\n * Defaults to config.maxParticles ?? 256.\n */\n maxParticles?: number;\n /**\n * Initial LCG seed for deterministic particle randomness.\n * Defaults to 1. Call reseed() at any time to restart the sequence.\n */\n seed?: number;\n}\n\n/**\n * ParticleEmitter — emits particles based on a configuration.\n * Uses a ParticlePool for zero-GC operation.\n *\n * Call `update(dt)` each frame. Read `pool.particles` for rendering.\n */\nexport class ParticleEmitter {\n readonly config: EmitterConfig;\n readonly pool: ParticlePool;\n\n /** Emitter world position. */\n x = 0;\n y = 0;\n\n /** Whether the emitter is actively emitting. */\n emitting = true;\n\n private _emitAccumulator = 0;\n private _seed = 0;\n\n constructor(config: EmitterConfig, opts?: EmitterOptions) {\n this.config = config;\n const cap = opts?.maxParticles ?? config.maxParticles ?? 256;\n this.pool = new ParticlePool(cap);\n this._setSeed(opts?.seed ?? 1);\n }\n\n /** Reset the LCG seed — restarts the particle random sequence from this seed. */\n reseed(seed: number): void {\n this._setSeed(seed);\n }\n\n /** Normalize s into the valid Park-Miller domain [1, 2147483646]. */\n private _setSeed(s: number): void {\n let n = Number.isFinite(s) ? Math.floor(s) % 2147483647 : 0;\n if (n < 0) n += 2147483647;\n if (n === 0) n = 1;\n this._seed = n;\n }\n\n /** Update the emitter: emit new particles and update existing ones. */\n update(dt: number): void {\n if (this.emitting) {\n this._emitAccumulator += dt * this.config.rate;\n while (this._emitAccumulator >= 1) {\n this._emitAccumulator -= 1;\n if (!this._emitOne()) {\n this._emitAccumulator = 0;\n break;\n }\n }\n }\n\n this.pool.update(dt, this.config.gravityX ?? 0, this.config.gravityY ?? 0);\n }\n\n /** Emit a burst of particles. */\n burst(count: number): void {\n for (let i = 0; i < count; i++) {\n if (!this._emitOne()) break;\n }\n }\n\n /** Stop emitting and clear all particles. */\n reset(): void {\n this.emitting = false;\n this._emitAccumulator = 0;\n this.pool.clear();\n }\n\n /** Simple seeded pseudo-random for deterministic particles. */\n private _random(): number {\n this._seed = (this._seed * 16807) % 2147483647;\n return (this._seed - 1) / 2147483646;\n }\n\n /** Random float in [min, max]. */\n private _randomRange(min: number, max: number): number {\n return min + this._random() * (max - min);\n }\n\n /** Emit one particle. Returns false when the pool is at cap — caller should stop. */\n private _emitOne(): boolean {\n const p: Particle | null = this.pool.tryAcquire();\n if (!p) return false;\n\n const c = this.config;\n\n p.x = this.x;\n p.y = this.y;\n\n const angle = c.direction + this._randomRange(-c.spread, c.spread);\n const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;\n p.vx = Math.cos(angle) * speed;\n p.vy = Math.sin(angle) * speed;\n\n const lifetime = c.lifetimeMax ? this._randomRange(c.lifetime, c.lifetimeMax) : c.lifetime;\n p.life = lifetime;\n p.maxLife = lifetime;\n\n p.startSize = c.startSize ?? 4;\n p.endSize = c.endSize ?? 0;\n\n p.startAlpha = c.startAlpha ?? 1;\n p.endAlpha = c.endAlpha ?? 0;\n\n if (c.startColor) {\n p.startR = c.startColor.r;\n p.startG = c.startColor.g;\n p.startB = c.startColor.b;\n }\n if (c.endColor) {\n p.endR = c.endColor.r;\n p.endG = c.endColor.g;\n p.endB = c.endColor.b;\n }\n\n if (c.angularVelocity !== undefined) {\n p.angularVelocity = c.angularVelocityMax\n ? this._randomRange(c.angularVelocity, c.angularVelocityMax)\n : c.angularVelocity;\n }\n\n return true;\n }\n}\n"],"mappings":";;;;AAqCA,SAAS,iBAA2B;CAClC,OAAO;EACL,GAAG;EACH,GAAG;EACH,IAAI;EACJ,IAAI;EACJ,MAAM;EACN,SAAS;EACT,WAAW;EACX,SAAS;EACT,YAAY;EACZ,UAAU;EACV,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,MAAM;EACN,MAAM;EACN,MAAM;EACN,UAAU;EACV,iBAAiB;EACjB,QAAQ;CACV;AACF;;AAGA,SAAS,cAAc,GAAmB;CACxC,EAAE,IAAI;CACN,EAAE,IAAI;CACN,EAAE,KAAK;CACP,EAAE,KAAK;CACP,EAAE,OAAO;CACT,EAAE,UAAU;CACZ,EAAE,YAAY;CACd,EAAE,UAAU;CACZ,EAAE,aAAa;CACf,EAAE,WAAW;CACb,EAAE,SAAS;CACX,EAAE,SAAS;CACX,EAAE,SAAS;CACX,EAAE,OAAO;CACT,EAAE,OAAO;CACT,EAAE,OAAO;CACT,EAAE,WAAW;CACb,EAAE,kBAAkB;CACpB,EAAE,SAAS;AACb;;;;;AAMA,IAAa,eAAb,MAA0B;CACxB;CACA,UAA8B,CAAC;CAE/B,YAAY,WAAW,KAAK;EAC1B,KAAK,QAAQ,IAAIA,mBAAAA,KAAK,gBAAgB,eAAe,EAAE,SAAS,CAAC;EACjE,KAAK,MAAM,QAAQ,QAAQ;CAC7B;;CAGA,IAAI,cAAsB;EACxB,OAAO,KAAK,QAAQ;CACtB;;;;;;;CAQA,IAAI,UAAkB;EACpB,OAAO,KAAK,MAAM;CACpB;;CAGA,IAAI,YAAiC;EACnC,OAAO,KAAK;CACd;;CAGA,UAAoB;EAClB,MAAM,IAAI,KAAK,MAAM,QAAQ;EAC7B,EAAE,SAAS;EACX,KAAK,QAAQ,KAAK,CAAC;E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draw-particles.ts","../src/emitter-shape.ts","../src/particle-pool.ts","../src/particle-emitter.ts"],"sourcesContent":["import type { ParticlePool } from './particle-pool.js';\n\n/**\n * The frame rectangle within a texture. Structural on purpose: it matches\n * `SpriteFrame` from `@flare-engine/assets` without this package depending on\n * it — extra members like `name` are simply ignored.\n */\nexport interface ParticleFrameLike {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * The one method this adapter needs from a sprite batch.\n *\n * Declared structurally so `@flare-engine/particles` keeps its two dependencies\n * (`core`, `math`) and stays usable with no renderer at all. A real\n * `SpriteBatch` from `@flare-engine/render` satisfies it; so does a test double.\n * The parameter list mirrors `SpriteBatch.drawRaw`.\n */\nexport interface ParticleBatchLike {\n drawRaw(\n image: unknown,\n srcX: number,\n srcY: number,\n srcW: number,\n srcH: number,\n dstX: number,\n dstY: number,\n dstW: number,\n dstH: number,\n effect?: unknown,\n anchorX?: number,\n anchorY?: number,\n alpha?: number,\n rotation?: number,\n stretch?: boolean,\n ): void;\n}\n\n/** Options for `drawParticles`. */\nexport interface DrawParticlesOptions {\n /**\n * A single effect applied to every particle in this call.\n *\n * Constant for the whole batch, and deliberately not per-particle: a batch\n * retains the effect *reference* until it flushes, so one mutable object\n * reused across the loop would give every particle the last particle's\n * values. Per-particle effects therefore cost one object per particle per\n * frame, which is exactly what this package exists to avoid — pass a constant\n * here, or build the loop yourself over `pool.particles`.\n */\n effect?: unknown;\n /** Anchor within the destination rect. Defaults to the centre (0.5, 0.5). */\n anchorX?: number;\n anchorY?: number;\n}\n\n/**\n * Queue every live particle into a caller-owned sprite batch.\n *\n * Zero-alloc: the loop reads the pool's active list directly, allocates nothing\n * per particle, and hands each one to `drawRaw` — so a steady-state emitter adds\n * no garbage. Size and alpha come from the pool's own interpolators, and\n * rotation from the particle.\n *\n * The batch is passed in rather than owned so particles share one batch, and one\n * flush, with the rest of the scene — the `drawInto` idiom used elsewhere in the\n * engine.\n *\n * ```ts\n * // once, outside the loop\n * const frame = sheet.frames.find((f) => f.name === 'spark')!;\n * // each frame, before the batch flushes\n * drawParticles(emitter.pool, batch, atlas.image, frame);\n * ```\n *\n * **Colour is not applied per particle.** The pool interpolates\n * `startR/G/B → endR/G/B`, but delivering that to a batch needs one effect\n * object per particle per frame (see `DrawParticlesOptions.effect`). Alpha *is*\n * applied, because `drawRaw` takes it as a number. For per-particle colour today,\n * write the loop yourself over `pool.particles` and accept the allocation.\n *\n * `image` and `frame` are separate parameters because they are separate\n * everywhere else in the engine — a frame is a rectangle within a texture and\n * does not carry the texture.\n */\nexport function drawParticles(\n pool: ParticlePool,\n batch: ParticleBatchLike,\n image: unknown,\n frame: ParticleFrameLike,\n options?: DrawParticlesOptions,\n): void {\n const particles = pool.particles;\n const count = particles.length;\n if (count === 0) return;\n\n const effect = options?.effect;\n const anchorX = options?.anchorX ?? 0.5;\n const anchorY = options?.anchorY ?? 0.5;\n const srcX = frame.x;\n const srcY = frame.y;\n const srcW = frame.w;\n const srcH = frame.h;\n\n for (let i = 0; i < count; i++) {\n const p = particles[i]!;\n const size = pool.getSize(p);\n // A fully shrunk or fully faded particle costs a draw call for nothing.\n if (size <= 0) continue;\n const alpha = pool.getAlpha(p);\n if (alpha <= 0) continue;\n\n batch.drawRaw(\n image,\n srcX,\n srcY,\n srcW,\n srcH,\n p.x,\n p.y,\n size,\n size,\n effect,\n anchorX,\n anchorY,\n alpha,\n p.rotation,\n );\n }\n}\n","/**\n * Emitter shapes — where a particle starts, not where it goes.\n *\n * The split matters, because `EmitterConfig` already owns direction: `direction`\n * plus `spread` describe the velocity cone. A shape samples a **position offset**\n * from the emitter origin and reports the outward normal at that point, so the\n * two compose instead of competing. A shape with a meaningful outward direction\n * can opt velocity into it with `radial: true` — that is what turns a `ring`\n * from a circle of drifting particles into an explosion.\n */\n\n/** A filled disc of radius `radius`, sampled uniformly by area. */\nexport interface EmitterCircleShape {\n kind: 'circle';\n radius: number;\n /** Emit outward from the centre instead of along `config.direction`. */\n radial?: boolean;\n}\n\n/** An annulus at `radius`, `thickness` wide (default 0 — a bare ring). */\nexport interface EmitterRingShape {\n kind: 'ring';\n radius: number;\n thickness?: number;\n /** Emit outward from the centre instead of along `config.direction`. */\n radial?: boolean;\n}\n\n/** An axis-aligned rectangle centred on the emitter, sampled uniformly. */\nexport interface EmitterRectShape {\n kind: 'rect';\n width: number;\n height: number;\n}\n\n/**\n * A sector (wedge) of radius `radius` and half-angle `angle`, centred on\n * `config.direction` and sampled uniformly by area.\n *\n * This is a *position* wedge, which is what keeps it distinct from\n * `config.spread`: `spread` fans the velocity out of a single point, `cone`\n * spreads the spawn points themselves across the wedge.\n */\nexport interface EmitterConeShape {\n kind: 'cone';\n radius: number;\n angle: number;\n /** Emit outward from the apex instead of along `config.direction`. */\n radial?: boolean;\n}\n\n/** The emitter origin — every particle starts at the same point. The default. */\nexport interface EmitterPointShape {\n kind: 'point';\n}\n\n/** Where newly emitted particles are placed, relative to the emitter. */\nexport type EmitterShape =\n | EmitterPointShape\n | EmitterCircleShape\n | EmitterRingShape\n | EmitterRectShape\n | EmitterConeShape;\n\n/**\n * A sampled spawn point: an offset from the emitter origin, plus the outward\n * normal at that offset.\n *\n * `nx`/`ny` are unit length for the radial shapes. For `point` and `rect` there\n * is no meaningful outward direction and both are 0 — a caller honouring\n * `radial` must fall back to `config.direction`, which is what `hasRadialNormal`\n * is for.\n */\nexport interface ShapeSample {\n x: number;\n y: number;\n nx: number;\n ny: number;\n}\n\n/** A fresh, zeroed sample. Allocate once outside the loop and reuse. */\nexport function createShapeSample(): ShapeSample {\n return { x: 0, y: 0, nx: 0, ny: 0 };\n}\n\nconst TAU = Math.PI * 2;\n\n/**\n * Does this shape produce a usable outward normal?\n *\n * True only when the shape is radial *and* opted in. Lets a caller decide\n * between the normal and `config.direction` without inspecting the union.\n */\nexport function hasRadialNormal(shape: EmitterShape): boolean {\n switch (shape.kind) {\n case 'circle':\n case 'ring':\n case 'cone':\n return shape.radial === true;\n default:\n return false;\n }\n}\n\n/**\n * Sample a spawn offset into `out`. Zero-alloc: nothing is constructed here, so\n * this is safe to call once per emitted particle in a steady-state loop.\n *\n * `rand` must return a float in [0, 1). Pass the emitter's seeded generator to\n * keep emission deterministic — every shape draws a fixed number of values per\n * call (`point` 0, `ring`/`rect` 2, `circle`/`cone` 2), so a given seed replays\n * exactly.\n *\n * `direction` orients `cone` and is ignored by every other shape.\n */\nexport function sampleEmitterShape(\n shape: EmitterShape,\n rand: () => number,\n out: ShapeSample,\n direction = 0,\n): ShapeSample {\n switch (shape.kind) {\n case 'point': {\n out.x = 0;\n out.y = 0;\n out.nx = 0;\n out.ny = 0;\n return out;\n }\n case 'circle': {\n const angle = rand() * TAU;\n // sqrt keeps the distribution uniform by area; without it particles\n // bunch toward the centre.\n const r = Math.sqrt(rand()) * Math.max(0, shape.radius);\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n out.x = cos * r;\n out.y = sin * r;\n out.nx = cos;\n out.ny = sin;\n return out;\n }\n case 'ring': {\n const angle = rand() * TAU;\n const thickness = Math.max(0, shape.thickness ?? 0);\n const base = Math.max(0, shape.radius);\n // Uniform across the band rather than by area: a ring is thin by\n // definition, and area-weighting a 1px band buys nothing.\n const r = base + (rand() - 0.5) * thickness;\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n out.x = cos * r;\n out.y = sin * r;\n out.nx = cos;\n out.ny = sin;\n return out;\n }\n case 'rect': {\n const w = Math.max(0, shape.width);\n const h = Math.max(0, shape.height);\n out.x = (rand() - 0.5) * w;\n out.y = (rand() - 0.5) * h;\n out.nx = 0;\n out.ny = 0;\n return out;\n }\n case 'cone': {\n const half = Math.max(0, shape.angle);\n const angle = direction + (rand() * 2 - 1) * half;\n const r = Math.sqrt(rand()) * Math.max(0, shape.radius);\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n out.x = cos * r;\n out.y = sin * r;\n out.nx = cos;\n out.ny = sin;\n return out;\n }\n }\n}\n","import { Pool } from '@flare-engine/core';\nimport type { Color } from '@flare-engine/math';\n\n/** A single particle. Managed by ParticlePool — not user-facing. */\nexport interface Particle {\n /** World position. */\n x: number;\n y: number;\n /** Velocity in pixels/second. */\n vx: number;\n vy: number;\n /** Time remaining in seconds. */\n life: number;\n /** Total lifetime for interpolation. */\n maxLife: number;\n /** Start/end size for interpolation. */\n startSize: number;\n endSize: number;\n /** Start/end alpha for interpolation. */\n startAlpha: number;\n endAlpha: number;\n /** Start/end color components for interpolation. */\n startR: number;\n startG: number;\n startB: number;\n endR: number;\n endG: number;\n endB: number;\n /** Rotation in radians. */\n rotation: number;\n /** Angular velocity in radians/second. */\n angularVelocity: number;\n /** Whether this particle is active. */\n active: boolean;\n}\n\n/** Create a default (inactive) particle. */\nfunction createParticle(): Particle {\n return {\n x: 0,\n y: 0,\n vx: 0,\n vy: 0,\n life: 0,\n maxLife: 0,\n startSize: 1,\n endSize: 1,\n startAlpha: 1,\n endAlpha: 0,\n startR: 1,\n startG: 1,\n startB: 1,\n endR: 1,\n endG: 1,\n endB: 1,\n rotation: 0,\n angularVelocity: 0,\n active: false,\n };\n}\n\n/** Reset a particle to default (inactive) state. */\nfunction resetParticle(p: Particle): void {\n p.x = 0;\n p.y = 0;\n p.vx = 0;\n p.vy = 0;\n p.life = 0;\n p.maxLife = 0;\n p.startSize = 1;\n p.endSize = 1;\n p.startAlpha = 1;\n p.endAlpha = 0;\n p.startR = 1;\n p.startG = 1;\n p.startB = 1;\n p.endR = 1;\n p.endG = 1;\n p.endB = 1;\n p.rotation = 0;\n p.angularVelocity = 0;\n p.active = false;\n}\n\n/**\n * ParticlePool — pre-allocated pool of particles.\n * Zero GC pressure during steady-state gameplay.\n */\nexport class ParticlePool {\n private _pool: Pool<Particle>;\n private _active: Particle[] = [];\n\n constructor(capacity = 256) {\n this._pool = new Pool(createParticle, resetParticle, { capacity });\n this._pool.prewarm(capacity);\n }\n\n /** Number of currently active particles. */\n get activeCount(): number {\n return this._active.length;\n }\n\n /**\n * Cumulative factory calls made by the internal pool's acquire()/tryAcquire().\n * prewarm() is excluded: factory calls there pre-fill the free list and are\n * not counted. Intended use: snapshot before and after a frame — a non-zero\n * delta in steady state means unexpected allocation.\n */\n get created(): number {\n return this._pool.created;\n }\n\n /** Read-only access to active particles. */\n get particles(): readonly Particle[] {\n return this._active;\n }\n\n /** Acquire a particle from the pool. */\n acquire(): Particle {\n const p = this._pool.acquire();\n p.active = true;\n this._active.push(p);\n return p;\n }\n\n /**\n * Acquire a particle only if the pool is below capacity.\n * Returns null at cap — no allocation occurs.\n */\n tryAcquire(): Particle | null {\n const p = this._pool.tryAcquire();\n if (!p) return null;\n p.active = true;\n this._active.push(p);\n return p;\n }\n\n /** Update all active particles. Releases dead particles. */\n update(dt: number, gravityX: number, gravityY: number): void {\n let i = 0;\n while (i < this._active.length) {\n const p = this._active[i]!;\n p.life -= dt;\n\n if (p.life <= 0) {\n // Dead — release and swap-remove\n p.active = false;\n this._pool.release(p);\n this._active[i] = this._active[this._active.length - 1]!;\n this._active.pop();\n continue;\n }\n\n // Apply gravity\n p.vx += gravityX * dt;\n p.vy += gravityY * dt;\n\n // Integrate position\n p.x += p.vx * dt;\n p.y += p.vy * dt;\n\n // Rotate\n p.rotation += p.angularVelocity * dt;\n\n i++;\n }\n }\n\n /** Get interpolated size for a particle (0 = start, 1 = end of life). */\n getSize(p: Particle): number {\n const t = 1 - p.life / p.maxLife;\n return p.startSize + (p.endSize - p.startSize) * t;\n }\n\n /** Get interpolated alpha for a particle. */\n getAlpha(p: Particle): number {\n const t = 1 - p.life / p.maxLife;\n return p.startAlpha + (p.endAlpha - p.startAlpha) * t;\n }\n\n /** Shared color buffer — avoids per-call allocation in the render hot path. */\n private _colorBuf: Color = { r: 1, g: 1, b: 1, a: 1 };\n\n /**\n * Get interpolated color for a particle.\n *\n * Returns a shared buffer — read the values immediately, do not retain the\n * reference. For a fresh object call `getColorInto()` with your own out param.\n */\n getColor(p: Particle): Color {\n return this.getColorInto(p, this._colorBuf);\n }\n\n /** Zero-alloc variant — writes the interpolated color into `out`. */\n getColorInto(p: Particle, out: Color): Color {\n const t = 1 - p.life / p.maxLife;\n out.r = p.startR + (p.endR - p.startR) * t;\n out.g = p.startG + (p.endG - p.startG) * t;\n out.b = p.startB + (p.endB - p.startB) * t;\n out.a = p.startAlpha + (p.endAlpha - p.startAlpha) * t;\n return out;\n }\n\n /** Release all active particles back to pool. */\n clear(): void {\n for (const p of this._active) {\n p.active = false;\n this._pool.release(p);\n }\n this._active.length = 0;\n }\n}\n","import type { Color } from '@flare-engine/math';\nimport type { EmitterShape, ShapeSample } from './emitter-shape.js';\nimport { createShapeSample, hasRadialNormal, sampleEmitterShape } from './emitter-shape.js';\nimport type { Particle } from './particle-pool.js';\nimport { ParticlePool } from './particle-pool.js';\n\n/** Configuration for a ParticleEmitter. */\nexport interface EmitterConfig {\n /** Emission rate in particles per second. */\n rate: number;\n /** Particle lifetime in seconds. */\n lifetime: number;\n /** Min lifetime (if set, actual lifetime is random between lifetime and lifetimeMax). */\n lifetimeMax?: number;\n /** Initial speed in pixels/second. */\n speed: number;\n /** Max speed (random range). */\n speedMax?: number;\n /** Emission direction in radians (0 = right). */\n direction: number;\n /** Spread angle in radians (half-angle of the emission cone). */\n spread: number;\n /** Gravity in pixels/second² (applied each frame). */\n gravityX?: number;\n gravityY?: number;\n /** Start size and end size. */\n startSize?: number;\n endSize?: number;\n /** Start alpha and end alpha. */\n startAlpha?: number;\n endAlpha?: number;\n /** Start color. */\n startColor?: Color;\n /** End color. */\n endColor?: Color;\n /** Angular velocity range (radians/second). */\n angularVelocity?: number;\n angularVelocityMax?: number;\n /** Maximum active particles (used as pool capacity default when no opts.maxParticles given). */\n maxParticles?: number;\n /**\n * Where particles spawn, relative to the emitter position. Defaults to\n * `{ kind: 'point' }`, which is the pre-existing behaviour — every particle\n * starts exactly at `x`/`y`.\n *\n * A shape samples position only; `direction` and `spread` still govern\n * velocity, unless the shape sets `radial: true` (see `EmitterShape`).\n */\n shape?: EmitterShape;\n}\n\n/** Construction options for ParticleEmitter. */\nexport interface EmitterOptions {\n /**\n * Hard cap on simultaneously active particles.\n * Overrides config.maxParticles when provided.\n * Defaults to config.maxParticles ?? 256.\n */\n maxParticles?: number;\n /**\n * Initial LCG seed for deterministic particle randomness.\n * Defaults to 1. Call reseed() at any time to restart the sequence.\n */\n seed?: number;\n}\n\n/**\n * ParticleEmitter — emits particles based on a configuration.\n * Uses a ParticlePool for zero-GC operation.\n *\n * Call `update(dt)` each frame. Read `pool.particles` for rendering.\n */\nexport class ParticleEmitter {\n readonly config: EmitterConfig;\n readonly pool: ParticlePool;\n\n /** Emitter world position. */\n x = 0;\n y = 0;\n\n /** Whether the emitter is actively emitting. */\n emitting = true;\n\n private _emitAccumulator = 0;\n private _seed = 0;\n /** Reused spawn-offset buffer — one per emitter, never per particle. */\n private readonly _sample: ShapeSample = createShapeSample();\n /** Bound once at construction; binding per emit would allocate a closure. */\n private readonly _rand = (): number => this._random();\n\n constructor(config: EmitterConfig, opts?: EmitterOptions) {\n this.config = config;\n const cap = opts?.maxParticles ?? config.maxParticles ?? 256;\n this.pool = new ParticlePool(cap);\n this._setSeed(opts?.seed ?? 1);\n }\n\n /** Reset the LCG seed — restarts the particle random sequence from this seed. */\n reseed(seed: number): void {\n this._setSeed(seed);\n }\n\n /** Normalize s into the valid Park-Miller domain [1, 2147483646]. */\n private _setSeed(s: number): void {\n let n = Number.isFinite(s) ? Math.floor(s) % 2147483647 : 0;\n if (n < 0) n += 2147483647;\n if (n === 0) n = 1;\n this._seed = n;\n }\n\n /** Update the emitter: emit new particles and update existing ones. */\n update(dt: number): void {\n if (this.emitting) {\n this._emitAccumulator += dt * this.config.rate;\n while (this._emitAccumulator >= 1) {\n this._emitAccumulator -= 1;\n if (!this._emitOne()) {\n this._emitAccumulator = 0;\n break;\n }\n }\n }\n\n this.pool.update(dt, this.config.gravityX ?? 0, this.config.gravityY ?? 0);\n }\n\n /** Emit a burst of particles. */\n burst(count: number): void {\n for (let i = 0; i < count; i++) {\n if (!this._emitOne()) break;\n }\n }\n\n /** Stop emitting and clear all particles. */\n reset(): void {\n this.emitting = false;\n this._emitAccumulator = 0;\n this.pool.clear();\n }\n\n /** Simple seeded pseudo-random for deterministic particles. */\n private _random(): number {\n this._seed = (this._seed * 16807) % 2147483647;\n return (this._seed - 1) / 2147483646;\n }\n\n /** Random float in [min, max]. */\n private _randomRange(min: number, max: number): number {\n return min + this._random() * (max - min);\n }\n\n /** Emit one particle. Returns false when the pool is at cap — caller should stop. */\n private _emitOne(): boolean {\n const p: Particle | null = this.pool.tryAcquire();\n if (!p) return false;\n\n const c = this.config;\n\n // Shape sampling comes first so it consumes its random draws before the\n // velocity draws below — that ordering is what makes a given seed replay\n // identically, and it is why `point` deliberately draws nothing at all\n // (an emitter with no shape produces the exact pre-shape sequence).\n const shape = c.shape;\n if (shape === undefined || shape.kind === 'point') {\n p.x = this.x;\n p.y = this.y;\n const angle = c.direction + this._randomRange(-c.spread, c.spread);\n const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;\n p.vx = Math.cos(angle) * speed;\n p.vy = Math.sin(angle) * speed;\n } else {\n const s = sampleEmitterShape(shape, this._rand, this._sample, c.direction);\n p.x = this.x + s.x;\n p.y = this.y + s.y;\n // A radial shape emits along its own outward normal, fanned by `spread`;\n // otherwise `direction` still rules, exactly as for a point emitter.\n const base = hasRadialNormal(shape) ? Math.atan2(s.ny, s.nx) : c.direction;\n const angle = base + this._randomRange(-c.spread, c.spread);\n const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;\n p.vx = Math.cos(angle) * speed;\n p.vy = Math.sin(angle) * speed;\n }\n\n const lifetime = c.lifetimeMax ? this._randomRange(c.lifetime, c.lifetimeMax) : c.lifetime;\n p.life = lifetime;\n p.maxLife = lifetime;\n\n p.startSize = c.startSize ?? 4;\n p.endSize = c.endSize ?? 0;\n\n p.startAlpha = c.startAlpha ?? 1;\n p.endAlpha = c.endAlpha ?? 0;\n\n if (c.startColor) {\n p.startR = c.startColor.r;\n p.startG = c.startColor.g;\n p.startB = c.startColor.b;\n }\n if (c.endColor) {\n p.endR = c.endColor.r;\n p.endG = c.endColor.g;\n p.endB = c.endColor.b;\n }\n\n if (c.angularVelocity !== undefined) {\n p.angularVelocity = c.angularVelocityMax\n ? this._randomRange(c.angularVelocity, c.angularVelocityMax)\n : c.angularVelocity;\n }\n\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,SAAgB,cACd,MACA,OACA,OACA,OACA,SACM;CACN,MAAM,YAAY,KAAK;CACvB,MAAM,QAAQ,UAAU;CACxB,IAAI,UAAU,GAAG;CAEjB,MAAM,SAAS,SAAS;CACxB,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,OAAO,MAAM;CACnB,MAAM,OAAO,MAAM;CACnB,MAAM,OAAO,MAAM;CACnB,MAAM,OAAO,MAAM;CAEnB,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,KAAK;EAC9B,MAAM,IAAI,UAAU;EACpB,MAAM,OAAO,KAAK,QAAQ,CAAC;EAE3B,IAAI,QAAQ,GAAG;EACf,MAAM,QAAQ,KAAK,SAAS,CAAC;EAC7B,IAAI,SAAS,GAAG;EAEhB,MAAM,QACJ,OACA,MACA,MACA,MACA,MACA,EAAE,GACF,EAAE,GACF,MACA,MACA,QACA,SACA,SACA,OACA,EAAE,QACJ;CACF;AACF;;;;ACpDA,SAAgB,oBAAiC;CAC/C,OAAO;EAAE,GAAG;EAAG,GAAG;EAAG,IAAI;EAAG,IAAI;CAAE;AACpC;AAEA,MAAM,MAAM,KAAK,KAAK;;;;;;;AAQtB,SAAgB,gBAAgB,OAA8B;CAC5D,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK;EACL,KAAK,QACH,OAAO,MAAM,WAAW;EAC1B,SACE,OAAO;CACX;AACF;;;;;;;;;;;;AAaA,SAAgB,mBACd,OACA,MACA,KACA,YAAY,GACC;CACb,QA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AAU;EAEZ,EAAE,YAAY,EAAE,aAAa;EAC7B,EAAE,UAAU,EAAE,WAAW;EAEzB,EAAE,aAAa,EAAE,cAAc;EAC/B,EAAE,WAAW,EAAE,YAAY;EAE3B,IAAI,EAAE,YAAY;GAChB,EAAE,SAAS,EAAE,WAAW;GACxB,EAAE,SAAS,EAAE,WAAW;GACxB,EAAE,SAAS,EAAE,WAAW;EAC1B;EACA,IAAI,EAAE,UAAU;GACd,EAAE,OAAO,EAAE,SAAS;GACpB,EAAE,OAAO,EAAE,SAAS;GACpB,EAAE,OAAO,EAAE,SAAS;EACtB;EAEA,IAAI,EAAE,oBAAoB,KAAA,GACxB,EAAE,kBAAkB,EAAE,qBAClB,KAAK,aAAa,EAAE,iBAAiB,EAAE,kBAAkB,IACzD,EAAE;EAGR,OAAO;CACT;AACF"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,146 @@
1
1
  import { Pool } from "@flare-engine/core";
2
+ //#region src/draw-particles.ts
3
+ /**
4
+ * Queue every live particle into a caller-owned sprite batch.
5
+ *
6
+ * Zero-alloc: the loop reads the pool's active list directly, allocates nothing
7
+ * per particle, and hands each one to `drawRaw` — so a steady-state emitter adds
8
+ * no garbage. Size and alpha come from the pool's own interpolators, and
9
+ * rotation from the particle.
10
+ *
11
+ * The batch is passed in rather than owned so particles share one batch, and one
12
+ * flush, with the rest of the scene — the `drawInto` idiom used elsewhere in the
13
+ * engine.
14
+ *
15
+ * ```ts
16
+ * // once, outside the loop
17
+ * const frame = sheet.frames.find((f) => f.name === 'spark')!;
18
+ * // each frame, before the batch flushes
19
+ * drawParticles(emitter.pool, batch, atlas.image, frame);
20
+ * ```
21
+ *
22
+ * **Colour is not applied per particle.** The pool interpolates
23
+ * `startR/G/B → endR/G/B`, but delivering that to a batch needs one effect
24
+ * object per particle per frame (see `DrawParticlesOptions.effect`). Alpha *is*
25
+ * applied, because `drawRaw` takes it as a number. For per-particle colour today,
26
+ * write the loop yourself over `pool.particles` and accept the allocation.
27
+ *
28
+ * `image` and `frame` are separate parameters because they are separate
29
+ * everywhere else in the engine — a frame is a rectangle within a texture and
30
+ * does not carry the texture.
31
+ */
32
+ function drawParticles(pool, batch, image, frame, options) {
33
+ const particles = pool.particles;
34
+ const count = particles.length;
35
+ if (count === 0) return;
36
+ const effect = options?.effect;
37
+ const anchorX = options?.anchorX ?? .5;
38
+ const anchorY = options?.anchorY ?? .5;
39
+ const srcX = frame.x;
40
+ const srcY = frame.y;
41
+ const srcW = frame.w;
42
+ const srcH = frame.h;
43
+ for (let i = 0; i < count; i++) {
44
+ const p = particles[i];
45
+ const size = pool.getSize(p);
46
+ if (size <= 0) continue;
47
+ const alpha = pool.getAlpha(p);
48
+ if (alpha <= 0) continue;
49
+ batch.drawRaw(image, srcX, srcY, srcW, srcH, p.x, p.y, size, size, effect, anchorX, anchorY, alpha, p.rotation);
50
+ }
51
+ }
52
+ //#endregion
53
+ //#region src/emitter-shape.ts
54
+ /** A fresh, zeroed sample. Allocate once outside the loop and reuse. */
55
+ function createShapeSample() {
56
+ return {
57
+ x: 0,
58
+ y: 0,
59
+ nx: 0,
60
+ ny: 0
61
+ };
62
+ }
63
+ const TAU = Math.PI * 2;
64
+ /**
65
+ * Does this shape produce a usable outward normal?
66
+ *
67
+ * True only when the shape is radial *and* opted in. Lets a caller decide
68
+ * between the normal and `config.direction` without inspecting the union.
69
+ */
70
+ function hasRadialNormal(shape) {
71
+ switch (shape.kind) {
72
+ case "circle":
73
+ case "ring":
74
+ case "cone": return shape.radial === true;
75
+ default: return false;
76
+ }
77
+ }
78
+ /**
79
+ * Sample a spawn offset into `out`. Zero-alloc: nothing is constructed here, so
80
+ * this is safe to call once per emitted particle in a steady-state loop.
81
+ *
82
+ * `rand` must return a float in [0, 1). Pass the emitter's seeded generator to
83
+ * keep emission deterministic — every shape draws a fixed number of values per
84
+ * call (`point` 0, `ring`/`rect` 2, `circle`/`cone` 2), so a given seed replays
85
+ * exactly.
86
+ *
87
+ * `direction` orients `cone` and is ignored by every other shape.
88
+ */
89
+ function sampleEmitterShape(shape, rand, out, direction = 0) {
90
+ switch (shape.kind) {
91
+ case "point":
92
+ out.x = 0;
93
+ out.y = 0;
94
+ out.nx = 0;
95
+ out.ny = 0;
96
+ return out;
97
+ case "circle": {
98
+ const angle = rand() * TAU;
99
+ const r = Math.sqrt(rand()) * Math.max(0, shape.radius);
100
+ const cos = Math.cos(angle);
101
+ const sin = Math.sin(angle);
102
+ out.x = cos * r;
103
+ out.y = sin * r;
104
+ out.nx = cos;
105
+ out.ny = sin;
106
+ return out;
107
+ }
108
+ case "ring": {
109
+ const angle = rand() * TAU;
110
+ const thickness = Math.max(0, shape.thickness ?? 0);
111
+ const r = Math.max(0, shape.radius) + (rand() - .5) * thickness;
112
+ const cos = Math.cos(angle);
113
+ const sin = Math.sin(angle);
114
+ out.x = cos * r;
115
+ out.y = sin * r;
116
+ out.nx = cos;
117
+ out.ny = sin;
118
+ return out;
119
+ }
120
+ case "rect": {
121
+ const w = Math.max(0, shape.width);
122
+ const h = Math.max(0, shape.height);
123
+ out.x = (rand() - .5) * w;
124
+ out.y = (rand() - .5) * h;
125
+ out.nx = 0;
126
+ out.ny = 0;
127
+ return out;
128
+ }
129
+ case "cone": {
130
+ const half = Math.max(0, shape.angle);
131
+ const angle = direction + (rand() * 2 - 1) * half;
132
+ const r = Math.sqrt(rand()) * Math.max(0, shape.radius);
133
+ const cos = Math.cos(angle);
134
+ const sin = Math.sin(angle);
135
+ out.x = cos * r;
136
+ out.y = sin * r;
137
+ out.nx = cos;
138
+ out.ny = sin;
139
+ return out;
140
+ }
141
+ }
142
+ }
143
+ //#endregion
2
144
  //#region src/particle-pool.ts
3
145
  /** Create a default (inactive) particle. */
4
146
  function createParticle() {
@@ -175,6 +317,10 @@ var ParticleEmitter = class {
175
317
  emitting = true;
176
318
  _emitAccumulator = 0;
177
319
  _seed = 0;
320
+ /** Reused spawn-offset buffer — one per emitter, never per particle. */
321
+ _sample = createShapeSample();
322
+ /** Bound once at construction; binding per emit would allocate a closure. */
323
+ _rand = () => this._random();
178
324
  constructor(config, opts) {
179
325
  this.config = config;
180
326
  const cap = opts?.maxParticles ?? config.maxParticles ?? 256;
@@ -230,12 +376,23 @@ var ParticleEmitter = class {
230
376
  const p = this.pool.tryAcquire();
231
377
  if (!p) return false;
232
378
  const c = this.config;
233
- p.x = this.x;
234
- p.y = this.y;
235
- const angle = c.direction + this._randomRange(-c.spread, c.spread);
236
- const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;
237
- p.vx = Math.cos(angle) * speed;
238
- p.vy = Math.sin(angle) * speed;
379
+ const shape = c.shape;
380
+ if (shape === void 0 || shape.kind === "point") {
381
+ p.x = this.x;
382
+ p.y = this.y;
383
+ const angle = c.direction + this._randomRange(-c.spread, c.spread);
384
+ const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;
385
+ p.vx = Math.cos(angle) * speed;
386
+ p.vy = Math.sin(angle) * speed;
387
+ } else {
388
+ const s = sampleEmitterShape(shape, this._rand, this._sample, c.direction);
389
+ p.x = this.x + s.x;
390
+ p.y = this.y + s.y;
391
+ const angle = (hasRadialNormal(shape) ? Math.atan2(s.ny, s.nx) : c.direction) + this._randomRange(-c.spread, c.spread);
392
+ const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;
393
+ p.vx = Math.cos(angle) * speed;
394
+ p.vy = Math.sin(angle) * speed;
395
+ }
239
396
  const lifetime = c.lifetimeMax ? this._randomRange(c.lifetime, c.lifetimeMax) : c.lifetime;
240
397
  p.life = lifetime;
241
398
  p.maxLife = lifetime;
@@ -258,6 +415,6 @@ var ParticleEmitter = class {
258
415
  }
259
416
  };
260
417
  //#endregion
261
- export { ParticleEmitter, ParticlePool };
418
+ export { ParticleEmitter, ParticlePool, createShapeSample, drawParticles, hasRadialNormal, sampleEmitterShape };
262
419
 
263
420
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/particle-pool.ts","../src/particle-emitter.ts"],"sourcesContent":["import { Pool } from '@flare-engine/core';\nimport type { Color } from '@flare-engine/math';\n\n/** A single particle. Managed by ParticlePool — not user-facing. */\nexport interface Particle {\n /** World position. */\n x: number;\n y: number;\n /** Velocity in pixels/second. */\n vx: number;\n vy: number;\n /** Time remaining in seconds. */\n life: number;\n /** Total lifetime for interpolation. */\n maxLife: number;\n /** Start/end size for interpolation. */\n startSize: number;\n endSize: number;\n /** Start/end alpha for interpolation. */\n startAlpha: number;\n endAlpha: number;\n /** Start/end color components for interpolation. */\n startR: number;\n startG: number;\n startB: number;\n endR: number;\n endG: number;\n endB: number;\n /** Rotation in radians. */\n rotation: number;\n /** Angular velocity in radians/second. */\n angularVelocity: number;\n /** Whether this particle is active. */\n active: boolean;\n}\n\n/** Create a default (inactive) particle. */\nfunction createParticle(): Particle {\n return {\n x: 0,\n y: 0,\n vx: 0,\n vy: 0,\n life: 0,\n maxLife: 0,\n startSize: 1,\n endSize: 1,\n startAlpha: 1,\n endAlpha: 0,\n startR: 1,\n startG: 1,\n startB: 1,\n endR: 1,\n endG: 1,\n endB: 1,\n rotation: 0,\n angularVelocity: 0,\n active: false,\n };\n}\n\n/** Reset a particle to default (inactive) state. */\nfunction resetParticle(p: Particle): void {\n p.x = 0;\n p.y = 0;\n p.vx = 0;\n p.vy = 0;\n p.life = 0;\n p.maxLife = 0;\n p.startSize = 1;\n p.endSize = 1;\n p.startAlpha = 1;\n p.endAlpha = 0;\n p.startR = 1;\n p.startG = 1;\n p.startB = 1;\n p.endR = 1;\n p.endG = 1;\n p.endB = 1;\n p.rotation = 0;\n p.angularVelocity = 0;\n p.active = false;\n}\n\n/**\n * ParticlePool — pre-allocated pool of particles.\n * Zero GC pressure during steady-state gameplay.\n */\nexport class ParticlePool {\n private _pool: Pool<Particle>;\n private _active: Particle[] = [];\n\n constructor(capacity = 256) {\n this._pool = new Pool(createParticle, resetParticle, { capacity });\n this._pool.prewarm(capacity);\n }\n\n /** Number of currently active particles. */\n get activeCount(): number {\n return this._active.length;\n }\n\n /**\n * Cumulative factory calls made by the internal pool's acquire()/tryAcquire().\n * prewarm() is excluded: factory calls there pre-fill the free list and are\n * not counted. Intended use: snapshot before and after a frame — a non-zero\n * delta in steady state means unexpected allocation.\n */\n get created(): number {\n return this._pool.created;\n }\n\n /** Read-only access to active particles. */\n get particles(): readonly Particle[] {\n return this._active;\n }\n\n /** Acquire a particle from the pool. */\n acquire(): Particle {\n const p = this._pool.acquire();\n p.active = true;\n this._active.push(p);\n return p;\n }\n\n /**\n * Acquire a particle only if the pool is below capacity.\n * Returns null at cap — no allocation occurs.\n */\n tryAcquire(): Particle | null {\n const p = this._pool.tryAcquire();\n if (!p) return null;\n p.active = true;\n this._active.push(p);\n return p;\n }\n\n /** Update all active particles. Releases dead particles. */\n update(dt: number, gravityX: number, gravityY: number): void {\n let i = 0;\n while (i < this._active.length) {\n const p = this._active[i]!;\n p.life -= dt;\n\n if (p.life <= 0) {\n // Dead — release and swap-remove\n p.active = false;\n this._pool.release(p);\n this._active[i] = this._active[this._active.length - 1]!;\n this._active.pop();\n continue;\n }\n\n // Apply gravity\n p.vx += gravityX * dt;\n p.vy += gravityY * dt;\n\n // Integrate position\n p.x += p.vx * dt;\n p.y += p.vy * dt;\n\n // Rotate\n p.rotation += p.angularVelocity * dt;\n\n i++;\n }\n }\n\n /** Get interpolated size for a particle (0 = start, 1 = end of life). */\n getSize(p: Particle): number {\n const t = 1 - p.life / p.maxLife;\n return p.startSize + (p.endSize - p.startSize) * t;\n }\n\n /** Get interpolated alpha for a particle. */\n getAlpha(p: Particle): number {\n const t = 1 - p.life / p.maxLife;\n return p.startAlpha + (p.endAlpha - p.startAlpha) * t;\n }\n\n /** Shared color buffer — avoids per-call allocation in the render hot path. */\n private _colorBuf: Color = { r: 1, g: 1, b: 1, a: 1 };\n\n /**\n * Get interpolated color for a particle.\n *\n * Returns a shared buffer — read the values immediately, do not retain the\n * reference. For a fresh object call `getColorInto()` with your own out param.\n */\n getColor(p: Particle): Color {\n return this.getColorInto(p, this._colorBuf);\n }\n\n /** Zero-alloc variant — writes the interpolated color into `out`. */\n getColorInto(p: Particle, out: Color): Color {\n const t = 1 - p.life / p.maxLife;\n out.r = p.startR + (p.endR - p.startR) * t;\n out.g = p.startG + (p.endG - p.startG) * t;\n out.b = p.startB + (p.endB - p.startB) * t;\n out.a = p.startAlpha + (p.endAlpha - p.startAlpha) * t;\n return out;\n }\n\n /** Release all active particles back to pool. */\n clear(): void {\n for (const p of this._active) {\n p.active = false;\n this._pool.release(p);\n }\n this._active.length = 0;\n }\n}\n","import type { Color } from '@flare-engine/math';\nimport type { Particle } from './particle-pool.js';\nimport { ParticlePool } from './particle-pool.js';\n\n/** Configuration for a ParticleEmitter. */\nexport interface EmitterConfig {\n /** Emission rate in particles per second. */\n rate: number;\n /** Particle lifetime in seconds. */\n lifetime: number;\n /** Min lifetime (if set, actual lifetime is random between lifetime and lifetimeMax). */\n lifetimeMax?: number;\n /** Initial speed in pixels/second. */\n speed: number;\n /** Max speed (random range). */\n speedMax?: number;\n /** Emission direction in radians (0 = right). */\n direction: number;\n /** Spread angle in radians (half-angle of the emission cone). */\n spread: number;\n /** Gravity in pixels/second² (applied each frame). */\n gravityX?: number;\n gravityY?: number;\n /** Start size and end size. */\n startSize?: number;\n endSize?: number;\n /** Start alpha and end alpha. */\n startAlpha?: number;\n endAlpha?: number;\n /** Start color. */\n startColor?: Color;\n /** End color. */\n endColor?: Color;\n /** Angular velocity range (radians/second). */\n angularVelocity?: number;\n angularVelocityMax?: number;\n /** Maximum active particles (used as pool capacity default when no opts.maxParticles given). */\n maxParticles?: number;\n}\n\n/** Construction options for ParticleEmitter. */\nexport interface EmitterOptions {\n /**\n * Hard cap on simultaneously active particles.\n * Overrides config.maxParticles when provided.\n * Defaults to config.maxParticles ?? 256.\n */\n maxParticles?: number;\n /**\n * Initial LCG seed for deterministic particle randomness.\n * Defaults to 1. Call reseed() at any time to restart the sequence.\n */\n seed?: number;\n}\n\n/**\n * ParticleEmitter — emits particles based on a configuration.\n * Uses a ParticlePool for zero-GC operation.\n *\n * Call `update(dt)` each frame. Read `pool.particles` for rendering.\n */\nexport class ParticleEmitter {\n readonly config: EmitterConfig;\n readonly pool: ParticlePool;\n\n /** Emitter world position. */\n x = 0;\n y = 0;\n\n /** Whether the emitter is actively emitting. */\n emitting = true;\n\n private _emitAccumulator = 0;\n private _seed = 0;\n\n constructor(config: EmitterConfig, opts?: EmitterOptions) {\n this.config = config;\n const cap = opts?.maxParticles ?? config.maxParticles ?? 256;\n this.pool = new ParticlePool(cap);\n this._setSeed(opts?.seed ?? 1);\n }\n\n /** Reset the LCG seed — restarts the particle random sequence from this seed. */\n reseed(seed: number): void {\n this._setSeed(seed);\n }\n\n /** Normalize s into the valid Park-Miller domain [1, 2147483646]. */\n private _setSeed(s: number): void {\n let n = Number.isFinite(s) ? Math.floor(s) % 2147483647 : 0;\n if (n < 0) n += 2147483647;\n if (n === 0) n = 1;\n this._seed = n;\n }\n\n /** Update the emitter: emit new particles and update existing ones. */\n update(dt: number): void {\n if (this.emitting) {\n this._emitAccumulator += dt * this.config.rate;\n while (this._emitAccumulator >= 1) {\n this._emitAccumulator -= 1;\n if (!this._emitOne()) {\n this._emitAccumulator = 0;\n break;\n }\n }\n }\n\n this.pool.update(dt, this.config.gravityX ?? 0, this.config.gravityY ?? 0);\n }\n\n /** Emit a burst of particles. */\n burst(count: number): void {\n for (let i = 0; i < count; i++) {\n if (!this._emitOne()) break;\n }\n }\n\n /** Stop emitting and clear all particles. */\n reset(): void {\n this.emitting = false;\n this._emitAccumulator = 0;\n this.pool.clear();\n }\n\n /** Simple seeded pseudo-random for deterministic particles. */\n private _random(): number {\n this._seed = (this._seed * 16807) % 2147483647;\n return (this._seed - 1) / 2147483646;\n }\n\n /** Random float in [min, max]. */\n private _randomRange(min: number, max: number): number {\n return min + this._random() * (max - min);\n }\n\n /** Emit one particle. Returns false when the pool is at cap — caller should stop. */\n private _emitOne(): boolean {\n const p: Particle | null = this.pool.tryAcquire();\n if (!p) return false;\n\n const c = this.config;\n\n p.x = this.x;\n p.y = this.y;\n\n const angle = c.direction + this._randomRange(-c.spread, c.spread);\n const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;\n p.vx = Math.cos(angle) * speed;\n p.vy = Math.sin(angle) * speed;\n\n const lifetime = c.lifetimeMax ? this._randomRange(c.lifetime, c.lifetimeMax) : c.lifetime;\n p.life = lifetime;\n p.maxLife = lifetime;\n\n p.startSize = c.startSize ?? 4;\n p.endSize = c.endSize ?? 0;\n\n p.startAlpha = c.startAlpha ?? 1;\n p.endAlpha = c.endAlpha ?? 0;\n\n if (c.startColor) {\n p.startR = c.startColor.r;\n p.startG = c.startColor.g;\n p.startB = c.startColor.b;\n }\n if (c.endColor) {\n p.endR = c.endColor.r;\n p.endG = c.endColor.g;\n p.endB = c.endColor.b;\n }\n\n if (c.angularVelocity !== undefined) {\n p.angularVelocity = c.angularVelocityMax\n ? this._randomRange(c.angularVelocity, c.angularVelocityMax)\n : c.angularVelocity;\n }\n\n return true;\n }\n}\n"],"mappings":";;;AAqCA,SAAS,iBAA2B;CAClC,OAAO;EACL,GAAG;EACH,GAAG;EACH,IAAI;EACJ,IAAI;EACJ,MAAM;EACN,SAAS;EACT,WAAW;EACX,SAAS;EACT,YAAY;EACZ,UAAU;EACV,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,MAAM;EACN,MAAM;EACN,MAAM;EACN,UAAU;EACV,iBAAiB;EACjB,QAAQ;CACV;AACF;;AAGA,SAAS,cAAc,GAAmB;CACxC,EAAE,IAAI;CACN,EAAE,IAAI;CACN,EAAE,KAAK;CACP,EAAE,KAAK;CACP,EAAE,OAAO;CACT,EAAE,UAAU;CACZ,EAAE,YAAY;CACd,EAAE,UAAU;CACZ,EAAE,aAAa;CACf,EAAE,WAAW;CACb,EAAE,SAAS;CACX,EAAE,SAAS;CACX,EAAE,SAAS;CACX,EAAE,OAAO;CACT,EAAE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a;EAC7B,EAAE,UAAU,EAAE,WAAW;EAEzB,EAAE,aAAa,EAAE,cAAc;EAC/B,EAAE,WAAW,EAAE,YAAY;EAE3B,IAAI,EAAE,YAAY;GAChB,EAAE,SAAS,EAAE,WAAW;GACxB,EAAE,SAAS,EAAE,WAAW;GACxB,EAAE,SAAS,EAAE,WAAW;EAC1B;EACA,IAAI,EAAE,UAAU;GACd,EAAE,OAAO,EAAE,SAAS;GACpB,EAAE,OAAO,EAAE,SAAS;GACpB,EAAE,OAAO,EAAE,SAAS;EACtB;EAEA,IAAI,EAAE,oBAAoB,KAAA,GACxB,EAAE,kBAAkB,EAAE,qBAClB,KAAK,aAAa,EAAE,iBAAiB,EAAE,kBAAkB,IACzD,EAAE;EAGR,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/draw-particles.ts","../src/emitter-shape.ts","../src/particle-pool.ts","../src/particle-emitter.ts"],"sourcesContent":["import type { ParticlePool } from './particle-pool.js';\n\n/**\n * The frame rectangle within a texture. Structural on purpose: it matches\n * `SpriteFrame` from `@flare-engine/assets` without this package depending on\n * it — extra members like `name` are simply ignored.\n */\nexport interface ParticleFrameLike {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * The one method this adapter needs from a sprite batch.\n *\n * Declared structurally so `@flare-engine/particles` keeps its two dependencies\n * (`core`, `math`) and stays usable with no renderer at all. A real\n * `SpriteBatch` from `@flare-engine/render` satisfies it; so does a test double.\n * The parameter list mirrors `SpriteBatch.drawRaw`.\n */\nexport interface ParticleBatchLike {\n drawRaw(\n image: unknown,\n srcX: number,\n srcY: number,\n srcW: number,\n srcH: number,\n dstX: number,\n dstY: number,\n dstW: number,\n dstH: number,\n effect?: unknown,\n anchorX?: number,\n anchorY?: number,\n alpha?: number,\n rotation?: number,\n stretch?: boolean,\n ): void;\n}\n\n/** Options for `drawParticles`. */\nexport interface DrawParticlesOptions {\n /**\n * A single effect applied to every particle in this call.\n *\n * Constant for the whole batch, and deliberately not per-particle: a batch\n * retains the effect *reference* until it flushes, so one mutable object\n * reused across the loop would give every particle the last particle's\n * values. Per-particle effects therefore cost one object per particle per\n * frame, which is exactly what this package exists to avoid — pass a constant\n * here, or build the loop yourself over `pool.particles`.\n */\n effect?: unknown;\n /** Anchor within the destination rect. Defaults to the centre (0.5, 0.5). */\n anchorX?: number;\n anchorY?: number;\n}\n\n/**\n * Queue every live particle into a caller-owned sprite batch.\n *\n * Zero-alloc: the loop reads the pool's active list directly, allocates nothing\n * per particle, and hands each one to `drawRaw` — so a steady-state emitter adds\n * no garbage. Size and alpha come from the pool's own interpolators, and\n * rotation from the particle.\n *\n * The batch is passed in rather than owned so particles share one batch, and one\n * flush, with the rest of the scene — the `drawInto` idiom used elsewhere in the\n * engine.\n *\n * ```ts\n * // once, outside the loop\n * const frame = sheet.frames.find((f) => f.name === 'spark')!;\n * // each frame, before the batch flushes\n * drawParticles(emitter.pool, batch, atlas.image, frame);\n * ```\n *\n * **Colour is not applied per particle.** The pool interpolates\n * `startR/G/B → endR/G/B`, but delivering that to a batch needs one effect\n * object per particle per frame (see `DrawParticlesOptions.effect`). Alpha *is*\n * applied, because `drawRaw` takes it as a number. For per-particle colour today,\n * write the loop yourself over `pool.particles` and accept the allocation.\n *\n * `image` and `frame` are separate parameters because they are separate\n * everywhere else in the engine — a frame is a rectangle within a texture and\n * does not carry the texture.\n */\nexport function drawParticles(\n pool: ParticlePool,\n batch: ParticleBatchLike,\n image: unknown,\n frame: ParticleFrameLike,\n options?: DrawParticlesOptions,\n): void {\n const particles = pool.particles;\n const count = particles.length;\n if (count === 0) return;\n\n const effect = options?.effect;\n const anchorX = options?.anchorX ?? 0.5;\n const anchorY = options?.anchorY ?? 0.5;\n const srcX = frame.x;\n const srcY = frame.y;\n const srcW = frame.w;\n const srcH = frame.h;\n\n for (let i = 0; i < count; i++) {\n const p = particles[i]!;\n const size = pool.getSize(p);\n // A fully shrunk or fully faded particle costs a draw call for nothing.\n if (size <= 0) continue;\n const alpha = pool.getAlpha(p);\n if (alpha <= 0) continue;\n\n batch.drawRaw(\n image,\n srcX,\n srcY,\n srcW,\n srcH,\n p.x,\n p.y,\n size,\n size,\n effect,\n anchorX,\n anchorY,\n alpha,\n p.rotation,\n );\n }\n}\n","/**\n * Emitter shapes — where a particle starts, not where it goes.\n *\n * The split matters, because `EmitterConfig` already owns direction: `direction`\n * plus `spread` describe the velocity cone. A shape samples a **position offset**\n * from the emitter origin and reports the outward normal at that point, so the\n * two compose instead of competing. A shape with a meaningful outward direction\n * can opt velocity into it with `radial: true` — that is what turns a `ring`\n * from a circle of drifting particles into an explosion.\n */\n\n/** A filled disc of radius `radius`, sampled uniformly by area. */\nexport interface EmitterCircleShape {\n kind: 'circle';\n radius: number;\n /** Emit outward from the centre instead of along `config.direction`. */\n radial?: boolean;\n}\n\n/** An annulus at `radius`, `thickness` wide (default 0 — a bare ring). */\nexport interface EmitterRingShape {\n kind: 'ring';\n radius: number;\n thickness?: number;\n /** Emit outward from the centre instead of along `config.direction`. */\n radial?: boolean;\n}\n\n/** An axis-aligned rectangle centred on the emitter, sampled uniformly. */\nexport interface EmitterRectShape {\n kind: 'rect';\n width: number;\n height: number;\n}\n\n/**\n * A sector (wedge) of radius `radius` and half-angle `angle`, centred on\n * `config.direction` and sampled uniformly by area.\n *\n * This is a *position* wedge, which is what keeps it distinct from\n * `config.spread`: `spread` fans the velocity out of a single point, `cone`\n * spreads the spawn points themselves across the wedge.\n */\nexport interface EmitterConeShape {\n kind: 'cone';\n radius: number;\n angle: number;\n /** Emit outward from the apex instead of along `config.direction`. */\n radial?: boolean;\n}\n\n/** The emitter origin — every particle starts at the same point. The default. */\nexport interface EmitterPointShape {\n kind: 'point';\n}\n\n/** Where newly emitted particles are placed, relative to the emitter. */\nexport type EmitterShape =\n | EmitterPointShape\n | EmitterCircleShape\n | EmitterRingShape\n | EmitterRectShape\n | EmitterConeShape;\n\n/**\n * A sampled spawn point: an offset from the emitter origin, plus the outward\n * normal at that offset.\n *\n * `nx`/`ny` are unit length for the radial shapes. For `point` and `rect` there\n * is no meaningful outward direction and both are 0 — a caller honouring\n * `radial` must fall back to `config.direction`, which is what `hasRadialNormal`\n * is for.\n */\nexport interface ShapeSample {\n x: number;\n y: number;\n nx: number;\n ny: number;\n}\n\n/** A fresh, zeroed sample. Allocate once outside the loop and reuse. */\nexport function createShapeSample(): ShapeSample {\n return { x: 0, y: 0, nx: 0, ny: 0 };\n}\n\nconst TAU = Math.PI * 2;\n\n/**\n * Does this shape produce a usable outward normal?\n *\n * True only when the shape is radial *and* opted in. Lets a caller decide\n * between the normal and `config.direction` without inspecting the union.\n */\nexport function hasRadialNormal(shape: EmitterShape): boolean {\n switch (shape.kind) {\n case 'circle':\n case 'ring':\n case 'cone':\n return shape.radial === true;\n default:\n return false;\n }\n}\n\n/**\n * Sample a spawn offset into `out`. Zero-alloc: nothing is constructed here, so\n * this is safe to call once per emitted particle in a steady-state loop.\n *\n * `rand` must return a float in [0, 1). Pass the emitter's seeded generator to\n * keep emission deterministic — every shape draws a fixed number of values per\n * call (`point` 0, `ring`/`rect` 2, `circle`/`cone` 2), so a given seed replays\n * exactly.\n *\n * `direction` orients `cone` and is ignored by every other shape.\n */\nexport function sampleEmitterShape(\n shape: EmitterShape,\n rand: () => number,\n out: ShapeSample,\n direction = 0,\n): ShapeSample {\n switch (shape.kind) {\n case 'point': {\n out.x = 0;\n out.y = 0;\n out.nx = 0;\n out.ny = 0;\n return out;\n }\n case 'circle': {\n const angle = rand() * TAU;\n // sqrt keeps the distribution uniform by area; without it particles\n // bunch toward the centre.\n const r = Math.sqrt(rand()) * Math.max(0, shape.radius);\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n out.x = cos * r;\n out.y = sin * r;\n out.nx = cos;\n out.ny = sin;\n return out;\n }\n case 'ring': {\n const angle = rand() * TAU;\n const thickness = Math.max(0, shape.thickness ?? 0);\n const base = Math.max(0, shape.radius);\n // Uniform across the band rather than by area: a ring is thin by\n // definition, and area-weighting a 1px band buys nothing.\n const r = base + (rand() - 0.5) * thickness;\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n out.x = cos * r;\n out.y = sin * r;\n out.nx = cos;\n out.ny = sin;\n return out;\n }\n case 'rect': {\n const w = Math.max(0, shape.width);\n const h = Math.max(0, shape.height);\n out.x = (rand() - 0.5) * w;\n out.y = (rand() - 0.5) * h;\n out.nx = 0;\n out.ny = 0;\n return out;\n }\n case 'cone': {\n const half = Math.max(0, shape.angle);\n const angle = direction + (rand() * 2 - 1) * half;\n const r = Math.sqrt(rand()) * Math.max(0, shape.radius);\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n out.x = cos * r;\n out.y = sin * r;\n out.nx = cos;\n out.ny = sin;\n return out;\n }\n }\n}\n","import { Pool } from '@flare-engine/core';\nimport type { Color } from '@flare-engine/math';\n\n/** A single particle. Managed by ParticlePool — not user-facing. */\nexport interface Particle {\n /** World position. */\n x: number;\n y: number;\n /** Velocity in pixels/second. */\n vx: number;\n vy: number;\n /** Time remaining in seconds. */\n life: number;\n /** Total lifetime for interpolation. */\n maxLife: number;\n /** Start/end size for interpolation. */\n startSize: number;\n endSize: number;\n /** Start/end alpha for interpolation. */\n startAlpha: number;\n endAlpha: number;\n /** Start/end color components for interpolation. */\n startR: number;\n startG: number;\n startB: number;\n endR: number;\n endG: number;\n endB: number;\n /** Rotation in radians. */\n rotation: number;\n /** Angular velocity in radians/second. */\n angularVelocity: number;\n /** Whether this particle is active. */\n active: boolean;\n}\n\n/** Create a default (inactive) particle. */\nfunction createParticle(): Particle {\n return {\n x: 0,\n y: 0,\n vx: 0,\n vy: 0,\n life: 0,\n maxLife: 0,\n startSize: 1,\n endSize: 1,\n startAlpha: 1,\n endAlpha: 0,\n startR: 1,\n startG: 1,\n startB: 1,\n endR: 1,\n endG: 1,\n endB: 1,\n rotation: 0,\n angularVelocity: 0,\n active: false,\n };\n}\n\n/** Reset a particle to default (inactive) state. */\nfunction resetParticle(p: Particle): void {\n p.x = 0;\n p.y = 0;\n p.vx = 0;\n p.vy = 0;\n p.life = 0;\n p.maxLife = 0;\n p.startSize = 1;\n p.endSize = 1;\n p.startAlpha = 1;\n p.endAlpha = 0;\n p.startR = 1;\n p.startG = 1;\n p.startB = 1;\n p.endR = 1;\n p.endG = 1;\n p.endB = 1;\n p.rotation = 0;\n p.angularVelocity = 0;\n p.active = false;\n}\n\n/**\n * ParticlePool — pre-allocated pool of particles.\n * Zero GC pressure during steady-state gameplay.\n */\nexport class ParticlePool {\n private _pool: Pool<Particle>;\n private _active: Particle[] = [];\n\n constructor(capacity = 256) {\n this._pool = new Pool(createParticle, resetParticle, { capacity });\n this._pool.prewarm(capacity);\n }\n\n /** Number of currently active particles. */\n get activeCount(): number {\n return this._active.length;\n }\n\n /**\n * Cumulative factory calls made by the internal pool's acquire()/tryAcquire().\n * prewarm() is excluded: factory calls there pre-fill the free list and are\n * not counted. Intended use: snapshot before and after a frame — a non-zero\n * delta in steady state means unexpected allocation.\n */\n get created(): number {\n return this._pool.created;\n }\n\n /** Read-only access to active particles. */\n get particles(): readonly Particle[] {\n return this._active;\n }\n\n /** Acquire a particle from the pool. */\n acquire(): Particle {\n const p = this._pool.acquire();\n p.active = true;\n this._active.push(p);\n return p;\n }\n\n /**\n * Acquire a particle only if the pool is below capacity.\n * Returns null at cap — no allocation occurs.\n */\n tryAcquire(): Particle | null {\n const p = this._pool.tryAcquire();\n if (!p) return null;\n p.active = true;\n this._active.push(p);\n return p;\n }\n\n /** Update all active particles. Releases dead particles. */\n update(dt: number, gravityX: number, gravityY: number): void {\n let i = 0;\n while (i < this._active.length) {\n const p = this._active[i]!;\n p.life -= dt;\n\n if (p.life <= 0) {\n // Dead — release and swap-remove\n p.active = false;\n this._pool.release(p);\n this._active[i] = this._active[this._active.length - 1]!;\n this._active.pop();\n continue;\n }\n\n // Apply gravity\n p.vx += gravityX * dt;\n p.vy += gravityY * dt;\n\n // Integrate position\n p.x += p.vx * dt;\n p.y += p.vy * dt;\n\n // Rotate\n p.rotation += p.angularVelocity * dt;\n\n i++;\n }\n }\n\n /** Get interpolated size for a particle (0 = start, 1 = end of life). */\n getSize(p: Particle): number {\n const t = 1 - p.life / p.maxLife;\n return p.startSize + (p.endSize - p.startSize) * t;\n }\n\n /** Get interpolated alpha for a particle. */\n getAlpha(p: Particle): number {\n const t = 1 - p.life / p.maxLife;\n return p.startAlpha + (p.endAlpha - p.startAlpha) * t;\n }\n\n /** Shared color buffer — avoids per-call allocation in the render hot path. */\n private _colorBuf: Color = { r: 1, g: 1, b: 1, a: 1 };\n\n /**\n * Get interpolated color for a particle.\n *\n * Returns a shared buffer — read the values immediately, do not retain the\n * reference. For a fresh object call `getColorInto()` with your own out param.\n */\n getColor(p: Particle): Color {\n return this.getColorInto(p, this._colorBuf);\n }\n\n /** Zero-alloc variant — writes the interpolated color into `out`. */\n getColorInto(p: Particle, out: Color): Color {\n const t = 1 - p.life / p.maxLife;\n out.r = p.startR + (p.endR - p.startR) * t;\n out.g = p.startG + (p.endG - p.startG) * t;\n out.b = p.startB + (p.endB - p.startB) * t;\n out.a = p.startAlpha + (p.endAlpha - p.startAlpha) * t;\n return out;\n }\n\n /** Release all active particles back to pool. */\n clear(): void {\n for (const p of this._active) {\n p.active = false;\n this._pool.release(p);\n }\n this._active.length = 0;\n }\n}\n","import type { Color } from '@flare-engine/math';\nimport type { EmitterShape, ShapeSample } from './emitter-shape.js';\nimport { createShapeSample, hasRadialNormal, sampleEmitterShape } from './emitter-shape.js';\nimport type { Particle } from './particle-pool.js';\nimport { ParticlePool } from './particle-pool.js';\n\n/** Configuration for a ParticleEmitter. */\nexport interface EmitterConfig {\n /** Emission rate in particles per second. */\n rate: number;\n /** Particle lifetime in seconds. */\n lifetime: number;\n /** Min lifetime (if set, actual lifetime is random between lifetime and lifetimeMax). */\n lifetimeMax?: number;\n /** Initial speed in pixels/second. */\n speed: number;\n /** Max speed (random range). */\n speedMax?: number;\n /** Emission direction in radians (0 = right). */\n direction: number;\n /** Spread angle in radians (half-angle of the emission cone). */\n spread: number;\n /** Gravity in pixels/second² (applied each frame). */\n gravityX?: number;\n gravityY?: number;\n /** Start size and end size. */\n startSize?: number;\n endSize?: number;\n /** Start alpha and end alpha. */\n startAlpha?: number;\n endAlpha?: number;\n /** Start color. */\n startColor?: Color;\n /** End color. */\n endColor?: Color;\n /** Angular velocity range (radians/second). */\n angularVelocity?: number;\n angularVelocityMax?: number;\n /** Maximum active particles (used as pool capacity default when no opts.maxParticles given). */\n maxParticles?: number;\n /**\n * Where particles spawn, relative to the emitter position. Defaults to\n * `{ kind: 'point' }`, which is the pre-existing behaviour — every particle\n * starts exactly at `x`/`y`.\n *\n * A shape samples position only; `direction` and `spread` still govern\n * velocity, unless the shape sets `radial: true` (see `EmitterShape`).\n */\n shape?: EmitterShape;\n}\n\n/** Construction options for ParticleEmitter. */\nexport interface EmitterOptions {\n /**\n * Hard cap on simultaneously active particles.\n * Overrides config.maxParticles when provided.\n * Defaults to config.maxParticles ?? 256.\n */\n maxParticles?: number;\n /**\n * Initial LCG seed for deterministic particle randomness.\n * Defaults to 1. Call reseed() at any time to restart the sequence.\n */\n seed?: number;\n}\n\n/**\n * ParticleEmitter — emits particles based on a configuration.\n * Uses a ParticlePool for zero-GC operation.\n *\n * Call `update(dt)` each frame. Read `pool.particles` for rendering.\n */\nexport class ParticleEmitter {\n readonly config: EmitterConfig;\n readonly pool: ParticlePool;\n\n /** Emitter world position. */\n x = 0;\n y = 0;\n\n /** Whether the emitter is actively emitting. */\n emitting = true;\n\n private _emitAccumulator = 0;\n private _seed = 0;\n /** Reused spawn-offset buffer — one per emitter, never per particle. */\n private readonly _sample: ShapeSample = createShapeSample();\n /** Bound once at construction; binding per emit would allocate a closure. */\n private readonly _rand = (): number => this._random();\n\n constructor(config: EmitterConfig, opts?: EmitterOptions) {\n this.config = config;\n const cap = opts?.maxParticles ?? config.maxParticles ?? 256;\n this.pool = new ParticlePool(cap);\n this._setSeed(opts?.seed ?? 1);\n }\n\n /** Reset the LCG seed — restarts the particle random sequence from this seed. */\n reseed(seed: number): void {\n this._setSeed(seed);\n }\n\n /** Normalize s into the valid Park-Miller domain [1, 2147483646]. */\n private _setSeed(s: number): void {\n let n = Number.isFinite(s) ? Math.floor(s) % 2147483647 : 0;\n if (n < 0) n += 2147483647;\n if (n === 0) n = 1;\n this._seed = n;\n }\n\n /** Update the emitter: emit new particles and update existing ones. */\n update(dt: number): void {\n if (this.emitting) {\n this._emitAccumulator += dt * this.config.rate;\n while (this._emitAccumulator >= 1) {\n this._emitAccumulator -= 1;\n if (!this._emitOne()) {\n this._emitAccumulator = 0;\n break;\n }\n }\n }\n\n this.pool.update(dt, this.config.gravityX ?? 0, this.config.gravityY ?? 0);\n }\n\n /** Emit a burst of particles. */\n burst(count: number): void {\n for (let i = 0; i < count; i++) {\n if (!this._emitOne()) break;\n }\n }\n\n /** Stop emitting and clear all particles. */\n reset(): void {\n this.emitting = false;\n this._emitAccumulator = 0;\n this.pool.clear();\n }\n\n /** Simple seeded pseudo-random for deterministic particles. */\n private _random(): number {\n this._seed = (this._seed * 16807) % 2147483647;\n return (this._seed - 1) / 2147483646;\n }\n\n /** Random float in [min, max]. */\n private _randomRange(min: number, max: number): number {\n return min + this._random() * (max - min);\n }\n\n /** Emit one particle. Returns false when the pool is at cap — caller should stop. */\n private _emitOne(): boolean {\n const p: Particle | null = this.pool.tryAcquire();\n if (!p) return false;\n\n const c = this.config;\n\n // Shape sampling comes first so it consumes its random draws before the\n // velocity draws below — that ordering is what makes a given seed replay\n // identically, and it is why `point` deliberately draws nothing at all\n // (an emitter with no shape produces the exact pre-shape sequence).\n const shape = c.shape;\n if (shape === undefined || shape.kind === 'point') {\n p.x = this.x;\n p.y = this.y;\n const angle = c.direction + this._randomRange(-c.spread, c.spread);\n const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;\n p.vx = Math.cos(angle) * speed;\n p.vy = Math.sin(angle) * speed;\n } else {\n const s = sampleEmitterShape(shape, this._rand, this._sample, c.direction);\n p.x = this.x + s.x;\n p.y = this.y + s.y;\n // A radial shape emits along its own outward normal, fanned by `spread`;\n // otherwise `direction` still rules, exactly as for a point emitter.\n const base = hasRadialNormal(shape) ? Math.atan2(s.ny, s.nx) : c.direction;\n const angle = base + this._randomRange(-c.spread, c.spread);\n const speed = c.speedMax ? this._randomRange(c.speed, c.speedMax) : c.speed;\n p.vx = Math.cos(angle) * speed;\n p.vy = Math.sin(angle) * speed;\n }\n\n const lifetime = c.lifetimeMax ? this._randomRange(c.lifetime, c.lifetimeMax) : c.lifetime;\n p.life = lifetime;\n p.maxLife = lifetime;\n\n p.startSize = c.startSize ?? 4;\n p.endSize = c.endSize ?? 0;\n\n p.startAlpha = c.startAlpha ?? 1;\n p.endAlpha = c.endAlpha ?? 0;\n\n if (c.startColor) {\n p.startR = c.startColor.r;\n p.startG = c.startColor.g;\n p.startB = c.startColor.b;\n }\n if (c.endColor) {\n p.endR = c.endColor.r;\n p.endG = c.endColor.g;\n p.endB = c.endColor.b;\n }\n\n if (c.angularVelocity !== undefined) {\n p.angularVelocity = c.angularVelocityMax\n ? this._randomRange(c.angularVelocity, c.angularVelocityMax)\n : c.angularVelocity;\n }\n\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,SAAgB,cACd,MACA,OACA,OACA,OACA,SACM;CACN,MAAM,YAAY,KAAK;CACvB,MAAM,QAAQ,UAAU;CACxB,IAAI,UAAU,GAAG;CAEjB,MAAM,SAAS,SAAS;CACxB,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,OAAO,MAAM;CACnB,MAAM,OAAO,MAAM;CACnB,MAAM,OAAO,MAAM;CACnB,MAAM,OAAO,MAAM;CAEnB,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,KAAK;EAC9B,MAAM,IAAI,UAAU;EACpB,MAAM,OAAO,KAAK,QAAQ,CAAC;EAE3B,IAAI,QAAQ,GAAG;E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AAS,EAAE,SAAS;GACzE,EAAE,IAAI,KAAK,IAAI,EAAE;GACjB,EAAE,IAAI,KAAK,IAAI,EAAE;GAIjB,MAAM,SADO,gBAAgB,KAAK,IAAI,KAAK,MAAM,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,aAC5C,KAAK,aAAa,CAAC,EAAE,QAAQ,EAAE,MAAM;GAC1D,MAAM,QAAQ,EAAE,WAAW,KAAK,aAAa,EAAE,OAAO,EAAE,QAAQ,IAAI,EAAE;GACtE,EAAE,KAAK,KAAK,IAAI,KAAK,IAAI;GACzB,EAAE,KAAK,KAAK,IAAI,KAAK,IAAI;EAC3B;EAEA,MAAM,WAAW,EAAE,cAAc,KAAK,aAAa,EAAE,UAAU,EAAE,WAAW,IAAI,EAAE;EAClF,EAAE,OAAO;EACT,EAAE,UAAU;EAEZ,EAAE,YAAY,EAAE,aAAa;EAC7B,EAAE,UAAU,EAAE,WAAW;EAEzB,EAAE,aAAa,EAAE,cAAc;EAC/B,EAAE,WAAW,EAAE,YAAY;EAE3B,IAAI,EAAE,YAAY;GAChB,EAAE,SAAS,EAAE,WAAW;GACxB,EAAE,SAAS,EAAE,WAAW;GACxB,EAAE,SAAS,EAAE,WAAW;EAC1B;EACA,IAAI,EAAE,UAAU;GACd,EAAE,OAAO,EAAE,SAAS;GACpB,EAAE,OAAO,EAAE,SAAS;GACpB,EAAE,OAAO,EAAE,SAAS;EACtB;EAEA,IAAI,EAAE,oBAAoB,KAAA,GACxB,EAAE,kBAAkB,EAAE,qBAClB,KAAK,aAAa,EAAE,iBAAiB,EAAE,kBAAkB,IACzD,EAAE;EAGR,OAAO;CACT;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flare-engine/particles",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "Particle emitter, pool, immediate-mode Skia rendering",
5
5
  "keywords": ["flare-engine", "particles", "emitter", "skia"],
6
6
  "license": "Apache-2.0",
@@ -37,8 +37,8 @@
37
37
  "typecheck": "tsc --noEmit"
38
38
  },
39
39
  "dependencies": {
40
- "@flare-engine/core": "^0.3.1",
41
- "@flare-engine/math": "^0.3.1"
40
+ "@flare-engine/core": "^0.4.1",
41
+ "@flare-engine/math": "^0.4.1"
42
42
  },
43
43
  "engines": {
44
44
  "node": ">=20"