@silentstatestudio/perseon 0.0.0-stage → 0.1.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/LICENSE.md +73 -0
  3. package/README.md +849 -2
  4. package/dist/authoring/index.cjs +218 -0
  5. package/dist/authoring/index.d.cts +964 -0
  6. package/dist/authoring/index.d.ts +964 -0
  7. package/dist/authoring/index.js +219 -0
  8. package/dist/authoring/index.js.map +1 -0
  9. package/dist/chunk-443SQYAB.cjs +8468 -0
  10. package/dist/chunk-AVYXWDFD.js +8469 -0
  11. package/dist/chunk-AVYXWDFD.js.map +1 -0
  12. package/dist/chunk-BEDH7OYG.js +5484 -0
  13. package/dist/chunk-BEDH7OYG.js.map +1 -0
  14. package/dist/chunk-WEQPSGPS.cjs +5482 -0
  15. package/dist/chunk-ZIMCQTYK.cjs +6 -0
  16. package/dist/chunk-ZTG42LPX.js +6 -0
  17. package/dist/chunk-ZTG42LPX.js.map +1 -0
  18. package/dist/colors-CCeWL9q4.d.cts +2597 -0
  19. package/dist/colors-CGWrMf4V.d.ts +2597 -0
  20. package/dist/core/index.cjs +34 -0
  21. package/dist/core/index.d.cts +40 -0
  22. package/dist/core/index.d.ts +40 -0
  23. package/dist/core/index.js +35 -0
  24. package/dist/core/index.js.map +1 -0
  25. package/dist/index.cjs +34 -0
  26. package/dist/index.d.cts +3 -0
  27. package/dist/index.d.ts +3 -0
  28. package/dist/index.js +35 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/pixi-v7/index.cjs +587 -0
  31. package/dist/pixi-v7/index.d.cts +471 -0
  32. package/dist/pixi-v7/index.d.ts +471 -0
  33. package/dist/pixi-v7/index.js +588 -0
  34. package/dist/pixi-v7/index.js.map +1 -0
  35. package/dist/pixi-v8/index.cjs +679 -0
  36. package/dist/pixi-v8/index.d.cts +452 -0
  37. package/dist/pixi-v8/index.d.ts +452 -0
  38. package/dist/pixi-v8/index.js +680 -0
  39. package/dist/pixi-v8/index.js.map +1 -0
  40. package/dist/rendering-dYQXmGTV.d.cts +264 -0
  41. package/dist/rendering-dYQXmGTV.d.ts +264 -0
  42. package/dist/testing/index.cjs +182 -0
  43. package/dist/testing/index.d.cts +103 -0
  44. package/dist/testing/index.d.ts +103 -0
  45. package/dist/testing/index.js +184 -0
  46. package/dist/testing/index.js.map +1 -0
  47. package/package.json +144 -5
package/README.md CHANGED
@@ -1,3 +1,850 @@
1
- # Temporary Holding Version
1
+ # Perseon Engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A particle engine for PixiJS on the web, written in TypeScript. The simulation is
4
+ renderer-agnostic; PixiJS v8 and v7 adapters ship with it.
5
+
6
+ ## Features
7
+
8
+ - **Compile once, play many.** An animation config is compiled into closures when
9
+ you load it, so playing one is cheap enough to do per impact.
10
+ - **Pooled playbacks.** A one-shot returns itself when it ends; a long-lived one
11
+ is yours to stop.
12
+ - **Customizable per instance.** Change a value, a node or a whole strategy on
13
+ one playback, before or while it runs, without touching the others.
14
+ - **Renderer-agnostic core.** The engine knows nothing about PixiJS; adapters
15
+ implement a small rendering interface.
16
+ - **Authored in Perseon Particle Studio**, the editor, exported as plain JSON,
17
+ played by your game.
18
+
19
+ ## Installation
20
+
21
+ <!-- readme-sync: not-tested (shell command) -->
22
+ ```bash
23
+ npm install @silentstatestudio/perseon
24
+ ```
25
+
26
+ - **PixiJS:** `pixi.js` is an optional peer dependency, `^7.0.0 || ^8.5.2`. Your
27
+ app installs and controls the PixiJS version; the core has no runtime
28
+ dependency on it. On v8, 8.5.0 and 8.5.1 are left out: destroying a particle
29
+ group throws there (fixed in 8.5.2). The v7 adapter works from 7.0.0.
30
+ - **Node:** 18 or later, for tooling, tests and SSR. The package is ES2022, ships
31
+ as ESM and CommonJS, and carries its type declarations.
32
+ - **TypeScript:** the subpaths (`/pixi-v8`, `/testing`…) are declared through
33
+ `package.json#exports`, so their types need `moduleResolution` `"bundler"`,
34
+ `"node16"` or `"nodenext"`; with `"node"` (`node10`) they do not resolve.
35
+
36
+ ## Quick start
37
+
38
+ The whole script of a page with PixiJS v8, as an ES module (it uses top-level
39
+ `await`): a fountain of sparks in the middle of the canvas. Any small image will
40
+ do as `spark.png`.
41
+
42
+ ```ts
43
+ import { Application, Assets } from 'pixi.js'
44
+ import { Perseon } from '@silentstatestudio/perseon/pixi-v8'
45
+
46
+ const app = new Application()
47
+ await app.init({ width: 800, height: 600 })
48
+ document.body.appendChild(app.canvas)
49
+
50
+ // Once loaded, the URL is a texture id a config can name.
51
+ await Assets.load('spark.png')
52
+
53
+ const perseon = new Perseon({ ticker: app.ticker })
54
+ const sparks = perseon.createAnimation({
55
+ formatVersion: 2,
56
+ emitters: [
57
+ {
58
+ emission: { rate: 40 },
59
+ particles: {
60
+ texture: 'spark.png',
61
+ lifetime: 1,
62
+ kinetics: { velocity: { angle: { min: 0, max: Math.PI * 2 }, magnitude: 120 } },
63
+ alpha: { value: 1, velocity: -1 },
64
+ },
65
+ },
66
+ ],
67
+ })
68
+ sparks.play({ parent: app.stage, x: 400, y: 300 })
69
+ ```
70
+
71
+ A game rarely writes a config by hand: Perseon Particle Studio, the editor,
72
+ exports it as a JSON file ([Loading a config file](#loading-a-config-file)),
73
+ together with the atlas its texture ids name ([Textures](#textures)).
74
+
75
+ On v8, `createPixiApplication(options)` creates and initializes the `Application`
76
+ for you, preferring WebGPU and falling back to WebGL, and resolves to
77
+ `{ app, backend }`. `preferWebGPU: false` asks for WebGL; an explicit Pixi
78
+ `preference` takes precedence over `preferWebGPU`, and every other option goes to
79
+ `app.init` untouched.
80
+
81
+ ## Usage
82
+
83
+ ```ts
84
+ import { Perseon } from '@silentstatestudio/perseon/pixi-v8'
85
+
86
+ // Once in the app: the integration owns the renderer, and gives every playback
87
+ // a single callback on your ticker.
88
+ const perseon = new Perseon({ ticker: app.ticker })
89
+
90
+ // Once per kind of effect — this is the expensive call, so it belongs with
91
+ // asset loading.
92
+ const explosion = perseon.createAnimation(explosionConfig)
93
+ const thruster = perseon.createAnimation(thrusterConfig)
94
+
95
+ // As often as you like. A one-shot needs no bookkeeping: when it runs out it
96
+ // detaches itself and goes back in the pool.
97
+ explosion.play({ parent: world, x: hit.x, y: hit.y })
98
+
99
+ // Or wait for it. `finished` resolves and never rejects.
100
+ const done = explosion.play({ parent: world, x, y }).finished
101
+
102
+ // A continuous effect is held and stopped by you.
103
+ const left = thruster.play({ parent: ship, x: -12, y: 8 })
104
+ left.stop()
105
+ ```
106
+
107
+ `ticker` is optional (Pixi's `Ticker.shared` by default). A Pixi `Ticker` is
108
+ recognized by its members (`deltaMS`, `deltaTime`, `elapsedMS`, `speed`, `add`,
109
+ `remove`, `addOnce`, `start`, `stop`) rather than with `instanceof`, so an
110
+ `app.ticker` from a second copy of pixi.js in the bundle is still wrapped. The
111
+ bundle should still hold one copy of pixi.js: textures resolve through the
112
+ `Assets` the package imports. Any other object is taken as an `ITicker`
113
+ (`add(fn)` and `remove(fn)`), and its callbacks must receive the delta in
114
+ milliseconds.
115
+
116
+ ### The three levels
117
+
118
+ | | what it is | how many | cost |
119
+ | ------------------ | ------------------------------------------ | ---------------------- | ------------- |
120
+ | `Perseon` | the integration — your renderer and ticker | one per app | negligible |
121
+ | `PerseonAnimation` | the template: one compiled config | one per kind of effect | paid at load |
122
+ | playback | the instance: one showing of it | many | pooled, cheap |
123
+
124
+ The template never changes after `createAnimation`: it holds a frozen copy of
125
+ the config. Everything you customize lives in an instance, and goes back to
126
+ factory when the instance returns to the pool. The one thing a template lets you
127
+ set is the default value of a local parameter ([below](#template-defaults)).
128
+
129
+ ### Loading a config file
130
+
131
+ The editor exports plain JSON. `parseAnimationOptions` turns a file (text or a
132
+ parsed object) into options, with readable errors for a file that is not an
133
+ animation:
134
+
135
+ ```ts
136
+ import { parseAnimationOptions } from '@silentstatestudio/perseon/pixi-v8'
137
+
138
+ const loaded = parseAnimationOptions(text)
139
+ const explosion = perseon.createAnimation(loaded)
140
+ ```
141
+
142
+ `text` is the content of the file, from `fetch` or an import. The file must carry
143
+ `formatVersion: 2`; one without it, or with another version, is rejected. Like
144
+ any config, it is validated whole: `createAnimation` throws at load, rather than
145
+ at the first `play()` in the middle of a game. What it throws, and where it says
146
+ the file is wrong, is in [Diagnostics and errors](#diagnostics-and-errors).
147
+
148
+ ### Textures
149
+
150
+ A config names textures by **id** — an id you registered beforehand, an atlas
151
+ frame typically. Resolution is synchronous and happens as particles spawn, so
152
+ the loader never fetches anything: it looks the id up in the renderer's asset
153
+ cache and nothing else. An id that resolves to nothing becomes an empty texture,
154
+ which renders as nothing at all — so load the atlas that was exported alongside
155
+ the animation, and load it **before** the animation resolves those ids.
156
+
157
+ The editor exports an atlas as a `.png` and a `.json` pair. `PixiV8ParticleAtlas`
158
+ loads it and publishes its frames, so the ids in the config resolve:
159
+
160
+ ```ts
161
+ import { PixiV8ParticleAtlas } from '@silentstatestudio/perseon/pixi-v8'
162
+
163
+ const atlas = new PixiV8ParticleAtlas()
164
+ const atlasData = await fetch('effects/particles.json').then((response) => response.json())
165
+ await atlas.load('effects/particles.png', atlasData)
166
+ const frameIds = atlas.frameIds // the ids a config may name
167
+ ```
168
+
169
+ `load(image, data)` takes the image as a URL or as a `Texture` of yours, and the
170
+ spritesheet data. A second `load` on the same atlas replaces what it had, and
171
+ `destroy()` unpublishes it. The spritesheet itself is kept in `Assets.cache` under
172
+ the atlas's `cacheKey`, `PARTICLE_ATLAS_CACHE_KEY` unless you give one:
173
+ `new PixiV8ParticleAtlas('effects')`. Each atlas needs its own `cacheKey`: `load`
174
+ throws, publishing nothing, if the key already holds an entry that is not that
175
+ atlas's own sheet (another atlas, or something your game stored there). So to
176
+ load again under the same keys with new atlas objects, `destroy()` the old ones
177
+ first. On v7, `PixiV7ParticleAtlas` does the same and
178
+ takes v7's spritesheet data. If you republish an atlas while animations use it,
179
+ call `perseon.renderer.clearTextureCache()` so the ids resolve against the new one.
180
+ The [Known limits](#known-limits) say how frame ids and images are shared.
181
+
182
+ A URL is not an exception, it is just an id you have to load first:
183
+
184
+ ```ts
185
+ await Assets.load('https://cdn.example.com/smoke.png')
186
+ // the URL is a cache id now, and a config may name it like any other
187
+ ```
188
+
189
+ ## Prepare, start, release
190
+
191
+ `play(options)` is `prepare(options).start(options.emit ?? true)`, with one
192
+ difference: who owns the instance when it ends by itself (`autoRelease`, [below](#play-or-prepare-autorelease)).
193
+ Split it when the instance needs something before it begins:
194
+
195
+ ```ts
196
+ const pb = impact.prepare({
197
+ parent: world,
198
+ x: hit.x,
199
+ y: hit.y,
200
+ params: { damage: weapon.damage },
201
+ autoRelease: true,
202
+ })
203
+ const chunk = pb.getEmitter('debris')!.getLayer('chunk')!
204
+ chunk.option('texture').set(MATERIAL[hit.material].texture)
205
+ chunk.option('color.value').set(MATERIAL[hit.material].tint)
206
+ pb.start()
207
+ ```
208
+
209
+ `prepare` takes an instance from the pool (or builds one), mounts it and applies
210
+ `x`, `y`, `seed`, `params`, `transform`, `timeScale` and `autoRelease`. Nothing is drawn yet.
211
+ `start()` begins the session, so what you customized is already there when the
212
+ first particle is rolled and the warm-up runs. `start()` with no argument emits,
213
+ like `play()`; `start(false)` begins without emitting.
214
+
215
+ Controlling a session:
216
+
217
+ - **`pause()`** freezes it; **`start()`** goes on where it was. `start()` on a
218
+ playback that is already running does nothing, and says so through
219
+ `diagnostics`.
220
+ - **`reset()`** starts the session over without ending it: no end is told, and
221
+ `finished` keeps waiting for the real one. Running, it begins again from its
222
+ seed, with the `emit` of its `start()`, and keeps running; paused, the session
223
+ is left empty and stays paused until `start()`; stopped, it only clears.
224
+
225
+ How an instance ends. Every end is told once, with its `reason`, to the
226
+ `onFinished` listeners and to `finished` alike:
227
+
228
+ - **By itself** (`'completed'`). Every emitter exhausted and no particle alive.
229
+ With `autoRelease` (the default of `play()`) the instance goes back to the
230
+ pool; without it (the default of `prepare()`) it is left stopped and yours.
231
+ - **`stop()`** (`'stopped'`). Stops updating and clears the session, also from a
232
+ pause; the instance stays yours, and `start()` begins a new session.
233
+ - **Closing the emitters.** `emitter.spawn = false` (or `play({ emit: false })`)
234
+ stops emitting and lets the live particles fade. The session does not end: an
235
+ emitter closed by you is not exhausted. Nor does it reopen by itself, even with
236
+ repeats left: one you closed, or that began with `start(false)`, emits again
237
+ when you set `spawn = true`.
238
+ - **`release()`** (`'released'`). Back to the pool at once. Call it when the
239
+ effect has faded, or when the game object that held it is gone.
240
+ - **`destroy()`** (`'destroyed'`), or the container it draws under destroyed by
241
+ you (`'hostDestroyed'`): the instance is destroyed, not pooled.
242
+
243
+ ```ts
244
+ const trail = fx.play({ parent: world })
245
+ trail.emitters.forEach((e) => (e.spawn = false)) // stop emitting; the live ones fade
246
+ setTimeout(() => trail.release(), 300) // and back to the pool
247
+ ```
248
+
249
+ ### Play or prepare: `autoRelease`
250
+
251
+ `autoRelease` says whether the instance goes back to the pool when it ends by
252
+ itself. It is an option of `play` and `prepare`, and a property of the playback.
253
+
254
+ - **`play()`: `true`.** Fire and forget: at its end the instance goes back to
255
+ the pool, and the handle you kept is over.
256
+ - **`prepare()`: `false`.** The playback is the game's. At its end it is left
257
+ stopped (`isRunning` false, `isFinished` true, off the ticker), the handle
258
+ stays alive, and `start()` plays it again as a new session, with what you set
259
+ on it. It goes back to the pool with `release()`, or when you set
260
+ `autoRelease = true` (at once, if it has already ended).
261
+
262
+ ```ts
263
+ const shot = muzzle.prepare({ parent: gun })
264
+ shot.start() // and again at every shot, once the last one ended
265
+ shot.release() // when the gun goes away
266
+ ```
267
+
268
+ A one-shot you split with `prepare` to customize it wants `autoRelease: true`,
269
+ or it waits for your `release()`. `stop()` never gives the instance back,
270
+ whatever `autoRelease` says. Set on a playback that is over, `autoRelease` does
271
+ nothing and says so. A playback built with `new PerseonPlayback` has no pool: its
272
+ natural end always leaves it stopped, for `start()` to play it again.
273
+
274
+ ### The handle
275
+
276
+ Every `prepare()` and `play()` returns a new handle, and the handle carries a
277
+ generation. When the instance goes back to the pool the generation moves on: the
278
+ old handle has `alive === false`, and whatever you ask of it is a no-op with a
279
+ diagnostic. A late `stop()` cannot reach whoever owns the instance now.
280
+
281
+ ```ts
282
+ const pb = fx.play({ parent: world })
283
+ pb.release()
284
+ const stillMine = pb.alive // false
285
+ pb.stop() // does nothing, and says so
286
+ ```
287
+
288
+ What a handle gives you — `param` and `option` handles, emitters and layers,
289
+ `transform`, the functions `on` returns — carries the same generation and dies
290
+ with it. Hold a handle only while you own the instance: until it finishes (with
291
+ `autoRelease`), or until you `release()` it.
292
+
293
+ ## Customizing an instance
294
+
295
+ Two verbs. `param(id)` is a local parameter declared at the root of the
296
+ animation. `option(path)` is any field of the config, on the playback, an emitter
297
+ or a layer. Both return a handle with `get()`, `set()`, `reset()`, `current` and
298
+ `describe()`.
299
+
300
+ ```ts
301
+ pb.param('power').set(0.9) // a number pins the value
302
+ pb.option('externalForces.gravity').set(300) // a node takes the shape it has in the JSON
303
+ pb.start()
304
+ pb.param('power').reset()
305
+ ```
306
+
307
+ - **`param(id).set(number | label)`** pins the value of a local: no draw, no
308
+ Linked evaluation, clipped to its domain. `set(config)` replaces its strategy
309
+ instead. The last call wins.
310
+ - **`option(path).set(config)`** takes the shape the JSON has at that path. It
311
+ validates everything before it touches anything, copies what you give it, and
312
+ clips numbers out of their domain with a warning. `get()` returns a copy.
313
+ - **`reset()`** removes the pin and the replacement. A local goes back to its
314
+ template default, if it has one, else to the config.
315
+
316
+ A particle-scoped local belongs to each particle: pinning it, unpinning it or
317
+ changing it with `set(config)` reaches only the particles born afterwards, and the
318
+ live ones keep their value (a Linked one keeps its Linked). To have them all share
319
+ a value from the start, pin it before `start()`. `param(id).set(config)` takes
320
+ effect at the next draw of its scope: the next showing, the next emission cycle or
321
+ the particles born after it, for every emitter that reads it.
322
+
323
+ A change takes effect the next time the engine reads that node, so it reaches
324
+ live particles only if the node is read every tick. `describe().stage` says when:
325
+
326
+ | stage | read | examples |
327
+ | -------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
328
+ | `immediate` | now | `performance.*`, a pinned local, `eventBindings` |
329
+ | `tick` | every tick | gravity, wind, damping, point forces, regions, `emission.rate` and `duration` (Fixed or Linked), `maxVelocity`, a Linked or modulated layer value |
330
+ | `birth` | when a particle is born | `lifetime`, `texture`, `color.value`, motion values, force factors |
331
+ | `cycle` | when an emission cycle arms | `emission.count`, `playback.interval`, Range or List `rate` |
332
+ | `session` | when `start()` begins the session | `startDelay`, `repeat`, `initialState.*`, a local drawn once per playback |
333
+ | `construction` | when the instance is built | `randomness.*`, `capacity.initialPoolSize`, `blendMode` |
334
+
335
+ `construction` nodes belong to the template: a `set` on them in an instance
336
+ throws. A Linked source must be of the same level as the node or above (playback,
337
+ emitter, layer, particle): an emitter cannot read a particle field.
338
+
339
+ ```ts
340
+ const gravityStage = pb.option('externalForces.gravity').describe().stage // 'tick'
341
+ const drawnStage = pb.param('power').describe().stage // 'session': drawn once per playback
342
+ pb.param('power').set(0.9)
343
+ const pinnedStage = pb.param('power').describe().stage // 'immediate': a pinned value is read now
344
+ ```
345
+
346
+ The emitter setters (`spawnRate`, `spawnDuration`, `repeat`…) and the playback
347
+ ones (`gravity`, `damping`, `wind`, `windVector`, `addPointForce`,
348
+ `updatePointForce`…) are shortcuts for `set`, and they persist:
349
+
350
+ ```ts
351
+ pb.getEmitter('debris')!.spawnDuration = 3
352
+ ```
353
+
354
+ A number out of its domain is clipped, with a warning:
355
+
356
+ ```ts
357
+ pb.param('power').set(5) // domain is [0, 1]: it becomes 1, with a warning
358
+ ```
359
+
360
+ `maxUpdateRate` and `warmUpMaxTicks`, on the playback and on an emitter, warn
361
+ through `diagnostics` when you give them `0` or a negative number, and leave the
362
+ value as it was. "No limit" is `Infinity`, through these setters (a config
363
+ cannot hold it). On the playback, the getter returns the value in force, which
364
+ is also the ceiling of every emitter's. On an emitter, `undefined` inherits the
365
+ playback's, and `option('performance.maxUpdateRate').reset()` goes back to the
366
+ template's; its getter returns what was assigned (or `undefined`), and the value
367
+ in force, the lower of its own and the playback's, is the emitter's
368
+ `effectiveMaxUpdateRate` and `effectiveWarmUpMaxTicks`.
369
+
370
+ Emitter, region and point force ids cannot contain a dot, so that
371
+ `option('pointForces.toCounter.position')` is never ambiguous; parameter names can,
372
+ and are used with `param(id)`. A layer's `pointForceFactors.<id>` also works for a
373
+ point force the instance added with `addPointForce`: a point force affects no layer
374
+ without a factor, so set one on the layers it should reach. Gravity, damping and wind
375
+ work the same way: a layer without `gravityFactor`, `dampingFactor` or `windFactor`
376
+ is not affected by that force.
377
+
378
+ The cost of a `set` is paid when you call it, not in `start()`: it recompiles
379
+ what it changes. An instance that goes back to the pool is as the factory left
380
+ it, so customizing every showing means paying it every time.
381
+
382
+ ### Template defaults
383
+
384
+ `animation.param(id)` sets the default of a local for the instances prepared
385
+ **after** it. It takes a number or a label, and has `get()` and `reset()`:
386
+
387
+ ```ts
388
+ fx.param('power').set(0.2)
389
+ const after = fx.prepare({ parent: world })
390
+ ```
391
+
392
+ A default is a pinned value. On a Range or List local it makes every instance
393
+ that inherits it a constant; to draw again in one instance, give it a full
394
+ strategy with `set`.
395
+
396
+ ### Locals and globals
397
+
398
+ A **local** is declared once at the root of the animation, with a mode (Fixed,
399
+ Range, List, Linked) and when it is drawn: `sampleScope` is `'playback'` (once
400
+ per showing), `'emitter'` (once per emission cycle) or `'particle'` (once per
401
+ particle). The game customizes it per instance with `param(id)`.
402
+
403
+ A **global** is a value of the game, such as `playerHealth` or `rain`. It has no
404
+ modes. You set it on `Perseon`, and every animation that declares it listens:
405
+
406
+ ```ts
407
+ perseon.setGlobalParameter('rain', 80)
408
+ rain.windVector = { angle: 0, magnitude: 40 }
409
+ ```
410
+
411
+ You may set a global before or after the animation exists. One that no animation
412
+ declares is not told: the game sets its state, and who reads it is not its
413
+ business. What is told ([below](#diagnostics-and-errors)), by each animation that
414
+ declares the global and once per animation and global, is a value it cannot take:
415
+ a label for a number global or a number for a label one, and a label it does not
416
+ know (in both cases that animation keeps the global's `value`), or a number out of
417
+ its domain (clipped to it). `NaN` and `Infinity` throw a `PerseonConfigError`.
418
+
419
+ ```ts
420
+ perseon.setGlobalParameter('rian', 80) // nobody declares 'rian': it is kept, and nothing is told
421
+ perseon.setGlobalParameter('rain', 'heavy') // warns: 'rain' is a number, the animation keeps its value
422
+ ```
423
+
424
+ A parameter name is 1 to 50 characters, unique among globals and locals, and
425
+ different from every field a Linked can read.
426
+
427
+ ## Events
428
+
429
+ An animation names its events, and layers and emitters bind them to a trigger
430
+ (`onSpawn`, `onDeath`, `onRegionEnter`, `onRegionExit`, `onEmitStart`,
431
+ `onEmitStop`, `onFinished`). You listen at three levels, with the same payload:
432
+
433
+ ```ts
434
+ const stopListening = pb.on('hit', ({ particle }) => sfx.play(`pb ${particle!.parentX}`))
435
+ fx.on('hit', ({ target, animation }) => sfx.play(target === pb && animation === fx ? 'animation' : '?'))
436
+ perseon.on('hit', ({ emitter, layer }) => sfx.play(`${emitter.id}/${layer?.id}`))
437
+ pb.start()
438
+ ```
439
+
440
+ | level | hears | lasts |
441
+ | -------------- | ------------------------------- | ---------------------------------------- |
442
+ | `pb.on` | that playback | until the instance goes back to the pool |
443
+ | `animation.on` | every playback of the animation | until `destroy()` |
444
+ | `perseon.on` | every animation | until `destroy()` |
445
+
446
+ Each returns an `Unsubscribe`. Delivery is synchronous, at the point of the loop
447
+ where the trigger happens, from playback to animation to `Perseon`. The payload is
448
+ `{ name, trigger, target, animation, emitter, layer, regionId, particle }`:
449
+ `target` is the handle of the playback, and `particle` a **copy** of the particle
450
+ at that moment (only for particle triggers). The copy is one per event, shared by
451
+ its listeners and read-only: its fields are getters, so assigning one throws, and
452
+ `{ ...particle }` sees none of them. To copy the data, `event.particle.toObject()`
453
+ (a plain object of your own); `JSON.stringify(event.particle)` works too.
454
+
455
+ `pb.on` and `animation.on` throw on a name the animation does not declare, and
456
+ list the ones it does. `perseon.on` does not check.
457
+
458
+ ```ts
459
+ pb.on('hti', () => undefined) // throws, and lists the events that exist: "Its events: hit."
460
+ ```
461
+
462
+ ## Space: transform and coordinates
463
+
464
+ An animation has its own space, with its root node wherever you mount it.
465
+ **Every coordinate the engine takes or gives is in that space**: the transform,
466
+ regions, point forces and `particle.x`/`particle.y`. `particle.parentX`/`parentY`
467
+ add the playback's `x` and `y`. The emitter never moves.
468
+
469
+ The playback, each emitter and each layer have a `transform` of `{ x, y }`, `{ 0, 0 }`
470
+ by default. It moves **where new particles are born**:
471
+
472
+ <!-- readme-sync: not-tested (a formula, not code) -->
473
+ ```text
474
+ birth position = the layer's position (point, area or list)
475
+ + layer.transform + emitter.transform + playback.transform
476
+ ```
477
+
478
+ ```ts
479
+ const trail = fx.prepare({ parent: world, x: 100, y: 0 })
480
+ trail.transform.x = ship.x
481
+ trail.transform.y = ship.y
482
+ trail.getEmitter('debris')!.transform.x = 1
483
+ trail.getEmitter('debris')!.getLayer('chunk')!.transform.x = 2
484
+ trail.start()
485
+ ```
486
+
487
+ It does not move nodes or live particles, and it does not scale or rotate:
488
+ resizing, turning or moving the whole effect is the job of the container
489
+ (`parent`, the `x`/`y` of the playback, or one of your own). A trail is an
490
+ animation mounted in the world whose transform follows the ship: one number per
491
+ frame, whatever the shape of `kinetics.position`.
492
+
493
+ ## Composition
494
+
495
+ A level of motion (position, rotation, scale and alpha, each with its value and
496
+ its velocity) is composed, not replaced:
497
+
498
+ <!-- readme-sync: not-tested (a formula, not code) -->
499
+ ```text
500
+ value = stack(base + accumulator)
501
+ ```
502
+
503
+ - **base** is the strategy of the level: drawn at birth (Fixed, Range, List) or
504
+ read each tick (Linked).
505
+ - **accumulator** is what the level below integrates. In `kinetics.velocity` it
506
+ also gathers the forces whose factor the layer declares: gravity, wind, damping
507
+ and point forces.
508
+ - **stack** is the modifiers of the level, applied to the composed value.
509
+
510
+ So a Linked velocity does not cancel gravity, a modifier acts on the final value
511
+ and not on the base, and acceleration moves a particle with or without
512
+ `velocity`. Integration is semi-implicit: acceleration into velocity, the
513
+ `maxVelocity` clip, velocity into position.
514
+
515
+ Three cases that look different from a plain read of the config:
516
+
517
+ - An alpha pulse with a `multiply` modifier and a negative `velocity` fades
518
+ out.
519
+ - A rotation wobble with `add` and a `velocity` spins and wobbles.
520
+ - A `multiply` modifier on `magnitude` also brakes what gravity has
521
+ accumulated. A magnitude of 200 upwards, modulated by `1 - lifeProgress`, with
522
+ gravity 500, rises about 33 px and stops. That is by design, with no exception
523
+ for the velocity.
524
+
525
+ On polar vectors (`{ angle, magnitude }`) the base is polar and the accumulator
526
+ is cartesian. The stack of `angle` turns the final vector, so a wobble of `angle`
527
+ also swings the fall due to gravity; the stack of `magnitude` scales its length.
528
+
529
+ ## Time
530
+
531
+ `timeScale` multiplies the simulated step of one playback. The `maxUpdateRate`
532
+ gate works in real time, and what passes is scaled. `pause()` is unchanged.
533
+
534
+ ```ts
535
+ const slow = fx.play({ parent: world, timeScale: 0.2 })
536
+ const normal = fx.play({ parent: world })
537
+ slow.timeScale = 0.5
538
+ ```
539
+
540
+ A frame whose delta is not a finite, non-negative number of milliseconds (`NaN`,
541
+ `Infinity`, a negative number, or a Pixi 8 `Ticker` forwarded by mistake instead
542
+ of its `deltaMS`) advances nothing, and `diagnostics` reports it once. A delta
543
+ of 0 is ignored silently. It matters only for an `ITicker` of your own built on
544
+ a Pixi 8 ticker, whose listeners receive the ticker: forward `ticker.deltaMS`.
545
+
546
+ The warm-up (`initialState.simulateTime`) runs inside `start()`, in slices of at
547
+ least 1 ms (`WARM_UP_MIN_STEP_SECONDS`, in `@silentstatestudio/perseon/authoring`).
548
+ At a `maxUpdateRate` of 1000 Hz or less the slices are the clock's own; above it,
549
+ `Infinity` included, the same `simulateTime` takes at most
550
+ `ceil(simulateTime / 0.001)` ticks. `warmUpMaxTicks` caps them.
551
+
552
+ ## Describing an animation
553
+
554
+ `animation.describe()` returns the globals, the locals (with their
555
+ `sampleScope`), the events, the emitters and layers by id, and the ids of point
556
+ forces and regions. A debug panel needs nothing else:
557
+
558
+ ```ts
559
+ const { globalParameters, localParameters, events, emitters, pointForces, regions } = boom.describe()
560
+ for (const p of localParameters) guiApi.add(p.label, p.domain, (v) => live.param(p.id).set(v))
561
+ ```
562
+
563
+ Each control drives the instance, not the animation. A parameter handle describes
564
+ itself too: `path`, `kind`, `stage`, `strategy`, `mode`, `domain`, `overridden`,
565
+ `pinned` and `active`.
566
+
567
+ ## Diagnostics and errors
568
+
569
+ Two kinds of failure, two answers.
570
+
571
+ **A config Perseon rejects** is a `PerseonConfigError`, always: when a config is
572
+ loaded (`createAnimation`, `parseAnimationOptions`) and when `set` receives
573
+ something the format does not have. `path` says where, and a failed `set` changes
574
+ nothing.
575
+
576
+ ```ts
577
+ import { PerseonConfigError } from '@silentstatestudio/perseon/pixi-v8'
578
+
579
+ try {
580
+ pb.option('externalForces.gravity').set('heavy' as never)
581
+ } catch (error) {
582
+ if (error instanceof PerseonConfigError) console.warn(error.path, error.message)
583
+ }
584
+ ```
585
+
586
+ At load, `path` is the field in the file, `emitters[1].emission.rate` or
587
+ `performance.maxUpdateRate`, except that regions, point forces and parameters
588
+ are named by their id: `ParticleAnimationOptions.regions['water'].area.radius`,
589
+ `ParticleAnimationOptions.pointForces['p1'].strength`. A value of the wrong shape
590
+ is reported the same way, never as a bare `TypeError` or `RangeError`; the error
591
+ underneath, if there was one, is its `cause`. A `"__proto__"` key is rejected, by
592
+ `createAnimation` and by `set`. Unknown keys are ignored.
593
+
594
+ Besides types and domains, loading checks the structure: a random list needs at
595
+ least one value; `capacity.maxAlive`, `capacity.initialPoolSize`,
596
+ `randomness.seed` and `performance` take plain numbers; emitter values and locals
597
+ take a number, a Range, a List or a Linked, but not the `{ base, modifiers }`
598
+ form, which only layers understand; emitter ids (optional) and layer ids within
599
+ an emitter are non-empty and unique, and event names are unique; a modulator
600
+ needs a known `shape`; color stops cannot go backwards; a polygon has
601
+ at least 3 points; and the booleans and strings of the format (a point force's
602
+ `enabled`, a sprite animation's `textures` and `animationLoop`, a label
603
+ parameter's `domain`) must be booleans and strings.
604
+
605
+ **A recoverable misuse** follows the `diagnostics` option of `Perseon`: a stale
606
+ handle, a number clipped to its domain, a global set to a value of the wrong type
607
+ or to a label its animation does not know, a Linked source that resolves to nothing.
608
+
609
+ | `diagnostics` | does |
610
+ | ------------------ | ---------------------------------------------------------- |
611
+ | `'warn'` (default) | prints it once per animation, with the `Perseon - ` prefix |
612
+ | `'throw'` | throws an `Error` with that message |
613
+ | `'silent'` | drops it |
614
+
615
+ ```ts
616
+ const strict = new Perseon({ ticker, diagnostics: 'throw' })
617
+ strict.createAnimation(rainConfig) // declares the global 'rain', a number
618
+ strict.setGlobalParameter('rain', 'heavy') // throws an Error that starts with "Perseon - "
619
+ ```
620
+
621
+ ## Particle classes
622
+
623
+ A `ParticleClass` extends `ParticleItem` to give its particles state and
624
+ behavior of their own. Override `onInit` (once, when a particle is born) and
625
+ `onUpdate` (every tick it lives), as methods or arrow-function fields; if the
626
+ subclass keeps state of its own, override `reset()`, call `super.reset()` and
627
+ clear that state there, because the engine pools particles and reuses them.
628
+
629
+ A hook may read every field of the particle and write its visual and physical
630
+ state (`x`, `y`, `velocityX`, `alpha`, `tint`…). A subclass cannot take over the
631
+ engine's own names: `init`, `updatePhysics`, `updateEnvironment` and
632
+ `updateTexture` (what the engine does with a particle) and `layer`, `mem`,
633
+ `bornX` and `bornY` (its per-particle state) are reserved, and declaring any of
634
+ them, with any visibility, is a compile error. In plain JavaScript nothing
635
+ checks it, so do not use those names there either.
636
+
637
+ What a hook receives is valid for that call and that playback: `emitter.id`,
638
+ `emitter.playback` (`start`, `stop`, `param`; a `start()` or `stop()` asked from
639
+ a hook applies at the end of the tick) and `rng`, the emitter's seeded generator.
640
+ Draw from it instead of `Math.random`, so a playback with the same `seed` replays
641
+ identically. Kept after the playback is over, `emitter.playback` is over too and
642
+ does nothing; the `particle` object is reborn as another particle after it dies,
643
+ so keep what you need from it, not the particle.
644
+
645
+ The class goes on the emitter, in code, since a JSON file cannot carry it:
646
+
647
+ ```ts
648
+ import { ParticleItem } from '@silentstatestudio/perseon/pixi-v8'
649
+ import type { ParameterInitOptions } from '@silentstatestudio/perseon/pixi-v8'
650
+
651
+ class Spark extends ParticleItem {
652
+ public override onInit({ particle, rng }: ParameterInitOptions) {
653
+ particle.tint = rng.next() < 0.5 ? 0xffcc00 : 0xff6600
654
+ }
655
+ }
656
+
657
+ const sparks = perseon.createAnimation({
658
+ ...sparkConfig,
659
+ emitters: sparkConfig.emitters.map((emitter) => ({ ...emitter, ParticleClass: Spark })),
660
+ })
661
+ ```
662
+
663
+ A layer can declare the same two hooks as functions, `onInit` and `onUpdate` in
664
+ its config.
665
+
666
+ ## Operations inside a listener
667
+
668
+ A lifecycle operation (`start`, `stop`, `reset`, `release`, `pause`, `destroy`,
669
+ `spawn`) or a `set` aimed at the instance that is **in its tick** is queued. That
670
+ covers a listener, the hooks of a [`ParticleClass`](#particle-classes), and
671
+ everything `start()` runs (draws, warm-up). Reads are immediate, and so are operations on other instances.
672
+
673
+ - **When.** The queue is applied at the end of the same tick, in the same
674
+ frame and before the render, in the order it was asked.
675
+ - **What you see inside.** Still the state of before: `isRunning` is `true` after
676
+ a `stop()` asked in the listener.
677
+ - **The tick goes on.** Asking is not stopping: the rest of the tick runs, so
678
+ several deaths in the same tick fire the listener several times.
679
+
680
+ ```ts
681
+ pb.on('hit', ({ target }) => {
682
+ target.stop() // applied when this tick ends
683
+ inside = target.isRunning // still true here
684
+ })
685
+ pb.start()
686
+ ```
687
+
688
+ If the tick spawns ten particles, `hit` is heard ten times and the `stop()` is
689
+ asked ten times. React once with a flag:
690
+
691
+ ```ts
692
+ let handled = false
693
+ pb.on('hit', ({ target }) => {
694
+ if (handled) return // the other spawns of this tick come here too
695
+ handled = true
696
+ target.stop()
697
+ })
698
+ ```
699
+
700
+ Calling `play()` from a listener is safe: the new playback runs from the next
701
+ frame.
702
+
703
+ What the operations ask in turn is applied right after them, in the same tick.
704
+ A listener that restarts its playback on an event the restart itself
705
+ brings back would never end, so the chain has a limit of 64 rounds: past it what
706
+ the operations asked is dropped (what was asked in the tick itself is still
707
+ applied), the playback is left as the last operation left it, and `diagnostics`
708
+ warns once. The warning names the emitters of the animation, the last event, the
709
+ operations that formed the round (`stop() + start()`) and how to fix it:
710
+
711
+ ```ts
712
+ // the warm-up kills particles, 'gone' fires on their death, and each restart does it again
713
+ pb.on('gone', ({ target }) => {
714
+ target.stop()
715
+ target.start()
716
+ })
717
+ pb.start() // returns, running, with a deferral warning
718
+ ```
719
+
720
+ Restart from an event the restart does not bring back, or react only once with a
721
+ flag as above.
722
+
723
+ ## Testing a game
724
+
725
+ `@silentstatestudio/perseon/testing` holds the doubles the engine's own tests run on. `Perseon` takes
726
+ any ticker, so a test pumps the frames itself:
727
+
728
+ ```ts
729
+ import { Container } from 'pixi.js'
730
+ import { Perseon, type PerseonPlayback } from '@silentstatestudio/perseon/pixi-v8'
731
+ import { FakeTicker } from '@silentstatestudio/perseon/testing'
732
+
733
+ const fake = new FakeTicker()
734
+ const testPerseon = new Perseon({ ticker: fake })
735
+ const fx = testPerseon.createAnimation(gameConfig)
736
+ const playback: PerseonPlayback = fx.play({ parent: new Container() })
737
+ fake.pump(1000 / 60)
738
+ ```
739
+
740
+ Nothing moves until you pump, and a frame of `1000 / 60` advances the simulation
741
+ by that much. `FakeRenderer`, also in `@silentstatestudio/perseon/testing`, serves tests that need no
742
+ Pixi at all, together with `@silentstatestudio/perseon/core`; `FakeRenderNode` and
743
+ `FakeParticleGroup` are the parts it builds, for a test that inspects what it drew.
744
+
745
+ ## Authoring tools
746
+
747
+ `@silentstatestudio/perseon/authoring` is for tools that write animations, not for games. It holds
748
+ the domains of every field, the catalogs a Linked reads from, `sanitizeName`, the
749
+ catalog of `option()` paths, `WARM_UP_MIN_STEP_SECONDS` and the format stamp:
750
+
751
+ ```ts
752
+ import { ANIMATION_FORMAT_VERSION, OPTION_PATH_CATALOG } from '@silentstatestudio/perseon/authoring'
753
+
754
+ const stamp = { formatVersion: ANIMATION_FORMAT_VERSION }
755
+ const layerPaths = OPTION_PATH_CATALOG.layer.map((entry) => entry.path)
756
+ ```
757
+
758
+ ## Entry points
759
+
760
+ | import | what it holds |
761
+ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
762
+ | `@silentstatestudio/perseon` | the engine, with no rendering library: `PerseonIntegration`, `PerseonPlayback` for hosts without a pool, `parseAnimationOptions`, `PerseonConfigError`, the classes and handles, the types |
763
+ | `@silentstatestudio/perseon/core` | the same engine, named explicitly |
764
+ | `@silentstatestudio/perseon/pixi-v8` | `Perseon` for PixiJS v8, `parseAnimationOptions`, `PerseonConfigError`, the renderer and its parts, `PixiV8ParticleAtlas`, `textureFromSource`, `createPixiApplication`, the classes and types |
765
+ | `@silentstatestudio/perseon/pixi-v7` | `Perseon` for PixiJS v7, with the same engine classes and types, its renderer and `PixiV7ParticleAtlas` |
766
+ | `@silentstatestudio/perseon/authoring` | domains, catalogs and checks for tools that write animations |
767
+ | `@silentstatestudio/perseon/testing` | `FakeTicker`, `FakeRenderer` and the parts it builds, `FakeRenderNode` and `FakeParticleGroup` |
768
+
769
+ The classes `Perseon` hands back (`PerseonAnimation`, `PerseonPlayback`,
770
+ `Emitter`, `ParticleLayer`, `ParticleItem`, and the handles `ParameterHandle`,
771
+ `LocalDefaultHandle` and `LocalParameterHandle`) are values in every entry but
772
+ `authoring` and `testing`, and the same class in each, so `instanceof` works
773
+ whichever you import. The adapters also export the types of their options and
774
+ members, such as `ITicker` and `IRenderer`, and the engine's: `OptionStage`,
775
+ `OptionStrategy`, `OptionNodeKind`, `CustomParameterSampleScope`, the event
776
+ triggers and `DiagnosticsPolicy`, among the rest of the format.
777
+
778
+ Each integration exports its own `Perseon`, under the same name and with the same
779
+ `Perseon` API, so moving between backends is changing one import line:
780
+
781
+ <!-- readme-sync: not-tested (a diff of one import line) -->
782
+ ```diff
783
+ -import { Perseon } from '@silentstatestudio/perseon/pixi-v8'
784
+ +import { Perseon } from '@silentstatestudio/perseon/pixi-v7'
785
+ ```
786
+
787
+ What differs is what that host has to hand over (a ticker, for both Pixi majors)
788
+ and what the renderer can draw. v7 has no `createPixiApplication` or
789
+ `resolveRendererBackend`, and it draws only the fixed-function blend modes
790
+ (`normal`, `add`, `multiply`, `screen` and `subtract`): it reports the rest as
791
+ `unsupported`, and they draw as `normal`. Everything above the renderer is shared,
792
+ so the backends cannot drift.
793
+
794
+ ## Known limits
795
+
796
+ **Layers cannot be interleaved across emitters.** Each emitter owns one render
797
+ node and creates its layers' groups inside it, in order, so the draw order of
798
+ `Emitter A [layer 1, layer 2]` + `Emitter B [layer 3, layer 4]` is exactly
799
+ 1, 2, 3, 4. Drawing layer 3 between layer 1 and layer 2 is not expressible: it
800
+ would have to leave the node-per-emitter hierarchy. Split the effect into more
801
+ emitters if you need a different order.
802
+
803
+ **Advanced blend modes need the back buffer on WebGL.** On Pixi v8 the ten modes
804
+ that are not fixed-function (Overlay, Color Dodge…) read what is already drawn,
805
+ and WebGL only keeps that with `useBackBuffer: true`. Without it Pixi warns and
806
+ the layer draws as `normal`. Pass it when you create the application:
807
+ `createPixiApplication({ useBackBuffer: true })`. WebGPU needs nothing. Each
808
+ advanced layer costs a full-screen pass per instance while it has live particles.
809
+ Under a filter on an ancestor with a reduced `filterArea`, the advanced pass
810
+ reads outside that filter's intermediate texture and is not supported: use the
811
+ fixed-function modes inside such filters.
812
+
813
+ **One base image per layer.** A particle layer can only draw textures that share
814
+ the same base image (the same atlas or source texture); particles from different
815
+ base images need separate layers.
816
+
817
+ **Atlas frame ids are global.** Every atlas frame is published as a global,
818
+ unprefixed key in `Assets.cache`. If an id is already used by an entry you put
819
+ there yourself (your own spritesheet, for instance), `load` throws and publishes
820
+ nothing, so keep your own ids distinct from the atlas frame ids. Between Perseon
821
+ atlases there is no such restriction: when two atlases publish the same id, the
822
+ last one to publish wins it, and the other leaves it alone when it is replaced or
823
+ destroyed.
824
+
825
+ **Who owns an atlas image.** An image URL that `Assets` already had loaded before
826
+ `atlas.load(url, data)` belongs to your game: `destroy()` and replacing the atlas
827
+ never unload it. An image the atlas loaded itself is unloaded when no atlas holds
828
+ it any more, so two atlases on the same URL share it safely.
829
+
830
+ **Seeded results hold within a version.** The same `seed` gives the same particles
831
+ on the same version of the package. Across `0.x` versions the sequence may change:
832
+ do not store frames or tests that depend on it across an upgrade.
833
+
834
+ ## Status
835
+
836
+ Work in progress. The API may change until the first stable release; the
837
+ [changelog](CHANGELOG.md) records each version. Website: <https://perseon.dev>.
838
+ Source and issues: <https://github.com/silentstatestudio/perseon>.
839
+ Support: <contact@silentstatestudio.com>. To contribute, read
840
+ [CONTRIBUTING.md](CONTRIBUTING.md).
841
+
842
+ ## License
843
+
844
+ Perseon Engine is source-available and free to use, under the
845
+ [PolyForm Perimeter License 1.0.1](LICENSE.md). You may use it, modify it and
846
+ redistribute it for any purpose, in personal and commercial projects, except to
847
+ provide others with a product that competes with Perseon Engine. Keep the license
848
+ and its copyright notice with any copy you pass on. Every JavaScript file of the
849
+ package starts with the license notice in a header comment; if your bundler strips
850
+ comments, keep the notice in your product's credits or in a third-party notices file.