@umicat/three-sdk 1.36.0 → 1.38.0

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.
@@ -14,8 +14,18 @@
14
14
  *
15
15
  * Version 2. A version-1 document (the upward-firing disc emitter of 1.35) is
16
16
  * still accepted: `parseVfx` upgrades it to the v2 emitter that plays the same.
17
+ *
18
+ * Version 4 (1.38) adds MESHES: mesh layers (`meshes`) and mesh-shaped
19
+ * particles (`emitter.mesh`), ADR-055 step 2. A 1.37 reader ignores unknown
20
+ * top-level fields, so meshes needed their own version to fail loudly there.
21
+ *
22
+ * Version 3 (1.37) adds the effect MATERIAL (`look: { type: 'material' }`,
23
+ * ADR-055). A document that uses none of it is still written as version 2 --
24
+ * `minimumVersion()` -- so games whose lockfile holds 1.36 keep playing it.
17
25
  */
18
- export const LIMITS = { emitters: 8, layers: 8, particles: 4000, cells: 4096, bursts: 16, children: 4, curvePoints: 8, gradientStops: 16 };
26
+ import { parseMaterial, materialTextures, materialDefaults } from './material.js';
27
+ import { parseMeshShape } from './mesh.js';
28
+ export const LIMITS = { emitters: 8, layers: 8, meshes: 8, particles: 4000, cells: 4096, bursts: 16, children: 4, curvePoints: 8, gradientStops: 16 };
19
29
  /** Every emitter field's value when a document leaves it out. */
20
30
  export function emitterDefaults() {
21
31
  return {
@@ -88,9 +98,14 @@ export function flipbookLayer(id, texture) {
88
98
  /** Every texture filename a document needs (flipbook sheets and particle images), once each. */
89
99
  export function vfxTextures(document) {
90
100
  const names = (document.flipbooks ?? []).map((f) => f.texture);
91
- for (const e of document.emitters)
101
+ for (const e of document.emitters) {
92
102
  if (e.look.type === 'texture' || e.look.type === 'sheet')
93
103
  names.push(e.look.texture);
104
+ else if (e.look.type === 'material')
105
+ names.push(...materialTextures(e.look.material));
106
+ }
107
+ for (const m of document.meshes ?? [])
108
+ names.push(...materialTextures(m.material));
94
109
  return [...new Set(names)];
95
110
  }
96
111
  // ---------------------------------------------------------------- sampling
@@ -167,8 +182,8 @@ export function parseVfx(value) {
167
182
  const d = structuredClone(value);
168
183
  const number = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
169
184
  const color = (v) => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v);
170
- if (d.version !== 2)
171
- fail('version must be 2 (or 1, which is upgraded)');
185
+ if (d.version !== 2 && d.version !== 3 && d.version !== 4)
186
+ fail(`version must be 2, 3 or 4 (or 1, which is upgraded)${typeof d.version === 'number' && d.version > 4 ? ` -- version ${d.version} was written by a newer editor: update @umicat/three-sdk` : ''}`);
172
187
  if (typeof d.name !== 'string' || !d.name.trim() || d.name.length > 80)
173
188
  fail('name must be 1-80 characters');
174
189
  if (!number(d.seed, 1, 2147483646) || !Number.isInteger(d.seed))
@@ -184,8 +199,12 @@ export function parseVfx(value) {
184
199
  if (d.flipbooks !== undefined && !Array.isArray(d.flipbooks))
185
200
  fail('flipbooks must be a list');
186
201
  const flipbooks = d.flipbooks ?? [];
202
+ if (d.meshes !== undefined && (!Array.isArray(d.meshes) || d.meshes.length > LIMITS.meshes))
203
+ fail(`meshes must be a list of 0-${LIMITS.meshes}`);
204
+ if (d.meshes !== undefined && d.version < 4)
205
+ fail('meshes are version 4: set "version": 4 (needs @umicat/three-sdk 1.38 or later)');
187
206
  const layers = d.emitters.length + flipbooks.length;
188
- if (layers < 1 || layers > LIMITS.layers)
207
+ if (layers > LIMITS.layers || layers + (d.meshes?.length ?? 0) < 1)
189
208
  fail(`an effect needs 1-${LIMITS.layers} layers (emitters + flipbooks), it has ${layers}`);
190
209
  const ids = new Set();
191
210
  const checkId = (id, at) => {
@@ -237,7 +256,7 @@ export function parseVfx(value) {
237
256
  fail(`${at} is not an object`);
238
257
  checkId(input.id, at);
239
258
  emitterIds.add(input.id);
240
- const known = new Set(['id', ...Object.keys(emitterDefaults()), ...CURVE_FIELDS, 'colorOverLife']);
259
+ const known = new Set(['id', ...Object.keys(emitterDefaults()), ...CURVE_FIELDS, 'colorOverLife', 'mesh', 'sizeOverLifeXYZ']);
241
260
  for (const key of Object.keys(input))
242
261
  if (!known.has(key))
243
262
  fail(`${at}.${key} is not an emitter field (a version-1 field? set "version": 1, or see emitterDefaults())`);
@@ -322,10 +341,35 @@ export function parseVfx(value) {
322
341
  fail(`${lat}.fps must be 1-120 or "life"`);
323
342
  }
324
343
  }
344
+ else if (l.type === 'material') {
345
+ if (d.version < 3)
346
+ fail(`${lat}.type "material" is version 3: set "version": 3 (needs @umicat/three-sdk 1.37 or later)`);
347
+ for (const k of Object.keys(l))
348
+ if (k !== 'type' && k !== 'material')
349
+ fail(`${lat}.${k} is not a field here (expected type, material)`);
350
+ l.material = parseMaterial(l.material, `${lat}.material`, fail, { checkCurve, checkGradient, texturePattern: TEXTURE_PATTERN });
351
+ }
325
352
  else
326
- fail(`${lat}.type must be dot, glow, star, texture or sheet`);
353
+ fail(`${lat}.type must be dot, glow, star, texture, sheet or material`);
327
354
  if (!['camera', 'velocity', 'ground', 'axis'].includes(e.align))
328
355
  fail(`${at}.align must be "camera", "velocity", "ground" or "axis"`);
356
+ if (e.sizeOverLifeXYZ !== undefined) {
357
+ if (d.version < 4)
358
+ fail(`${at}.sizeOverLifeXYZ is version 4: set "version": 4 (needs @umicat/three-sdk 1.38 or later)`);
359
+ const xyz = e.sizeOverLifeXYZ;
360
+ if (!xyz || typeof xyz !== 'object' || Array.isArray(xyz))
361
+ fail(`${at}.sizeOverLifeXYZ must be { x?, y?, z? } curves`);
362
+ for (const k of Object.keys(xyz)) {
363
+ if (!['x', 'y', 'z'].includes(k))
364
+ fail(`${at}.sizeOverLifeXYZ.${k} is not an axis (x, y, z)`);
365
+ checkCurve(xyz[k], `${at}.sizeOverLifeXYZ.${k}`);
366
+ }
367
+ }
368
+ if (e.mesh !== undefined) {
369
+ if (d.version < 4)
370
+ fail(`${at}.mesh is version 4: set "version": 4 (needs @umicat/three-sdk 1.38 or later)`);
371
+ e.mesh = parseMeshShape(e.mesh, `${at}.mesh`, fail);
372
+ }
329
373
  if (!['normal', 'additive'].includes(e.blend))
330
374
  fail(`${at}.blend must be "normal" or "additive"`);
331
375
  if (!Array.isArray(e.children) || e.children.length > LIMITS.children)
@@ -366,6 +410,45 @@ export function parseVfx(value) {
366
410
  const budget = particleBudget(d);
367
411
  if (budget > LIMITS.particles)
368
412
  fail(`too many live particles: the most this effect can have alive at once is about ${Math.ceil(budget)} (rate x lifetime + bursts, times sub-emitters), the limit is ${LIMITS.particles}`);
413
+ if (d.meshes)
414
+ d.meshes = d.meshes.map((raw, i) => {
415
+ const at = `meshes[${i}]`;
416
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
417
+ fail(`${at} is not an object`);
418
+ checkId(raw.id, at);
419
+ const base = meshLayerDefaults();
420
+ for (const k of Object.keys(raw))
421
+ if (!(k in base) && !['id', 'scaleOverLife', 'colorOverLife', 'alphaOverLife'].includes(k))
422
+ fail(`${at}.${k} is not a mesh-layer field (expected id, ${Object.keys(base).join(', ')}, scaleOverLife, colorOverLife, alphaOverLife)`);
423
+ const m = { ...base, ...raw };
424
+ if (typeof m.enabled !== 'boolean')
425
+ fail(`${at}.enabled must be a boolean`);
426
+ m.shape = parseMeshShape(m.shape, `${at}.shape`, fail);
427
+ checkVec(m.position, `${at}.position`, -100, 100);
428
+ checkVec(m.rotation, `${at}.rotation`, -360, 360);
429
+ checkVec(m.scale, `${at}.scale`, -100, 100);
430
+ if (m.facing !== 'none' && m.facing !== 'camera')
431
+ fail(`${at}.facing must be "none" or "camera"`);
432
+ if (!number(m.start, 0, 60))
433
+ fail(`${at}.start must be 0-60`);
434
+ if (m.life !== null && !number(m.life, .01, 60))
435
+ fail(`${at}.life must be null (to the end of the cycle) or 0.01-60`);
436
+ for (const k of ['scaleOverLife', 'alphaOverLife'])
437
+ if (m[k] !== undefined)
438
+ checkCurve(m[k], `${at}.${k}`);
439
+ if (!color(m.color))
440
+ fail(`${at}.color must be #rrggbb`);
441
+ if (m.colorOverLife !== undefined)
442
+ checkGradient(m.colorOverLife, `${at}.colorOverLife`);
443
+ if (!number(m.intensity, 0, 16))
444
+ fail(`${at}.intensity must be 0-16`);
445
+ if (m.blend !== 'normal' && m.blend !== 'additive')
446
+ fail(`${at}.blend must be "normal" or "additive"`);
447
+ if (!['front', 'back', 'both'].includes(m.side))
448
+ fail(`${at}.side must be "front", "back" or "both"`);
449
+ m.material = parseMaterial(m.material, `${at}.material`, fail, { checkCurve, checkGradient, texturePattern: TEXTURE_PATTERN });
450
+ return m;
451
+ });
369
452
  flipbooks.forEach((f, i) => {
370
453
  const at = `flipbooks[${i}]`;
371
454
  if (!f || typeof f !== 'object')
@@ -394,6 +477,25 @@ export function parseVfx(value) {
394
477
  });
395
478
  return d;
396
479
  }
480
+ /**
481
+ * The lowest format version that can express this document: 3 when any
482
+ * emitter uses the material look, else 2. The editor and the agent write
483
+ * this, so an effect that needs nothing new still plays on 1.36.
484
+ */
485
+ export function minimumVersion(d) {
486
+ if (d.emitters.some((e) => e.mesh !== undefined || e.sizeOverLifeXYZ !== undefined) || d.meshes !== undefined)
487
+ return 4;
488
+ return d.emitters.some((e) => e.look?.type === 'material') ? 3 : 2;
489
+ }
490
+ /** A new mesh layer: a soft additive ring on the ground, for the editor's "Add" and the agent. */
491
+ export function meshLayerDefaults() {
492
+ return {
493
+ enabled: true, shape: { type: 'ring', inner: .8, outer: 1 }, position: [0, .02, 0], rotation: [0, 0, 0], scale: [1, 1, 1],
494
+ facing: 'none', start: 0, life: null, color: '#ffffff', intensity: 1, blend: 'additive', side: 'both',
495
+ material: { ...materialDefaults(), masks: [] },
496
+ };
497
+ }
498
+ export function meshLayer(id, patch = {}) { return { id, ...meshLayerDefaults(), ...patch }; }
397
499
  /**
398
500
  * The most particles an effect can have alive at once, estimated: per enabled
399
501
  * emitter, rate x longest life plus every burst, and for sub-emitters, the
@@ -1,6 +1,8 @@
1
1
  export * from './document.js';
2
2
  export * from './templates.js';
3
3
  export { VfxInstance } from './VfxInstance.js';
4
+ export * from './material.js';
5
+ export * from './mesh.js';
4
6
  export type { VfxInstanceOptions, VfxTextureSource } from './VfxInstance.js';
5
7
  export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
6
8
  export type { LoadVfxOptions } from './load.js';
package/dist/vfx/index.js CHANGED
@@ -6,4 +6,6 @@
6
6
  export * from './document.js';
7
7
  export * from './templates.js';
8
8
  export { VfxInstance } from './VfxInstance.js';
9
+ export * from './material.js';
10
+ export * from './mesh.js';
9
11
  export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
@@ -0,0 +1,215 @@
1
+ /**
2
+ * The effect MATERIAL (format v3, umicat-design ADR-055): how a particle (and,
3
+ * later, a mesh layer) is drawn. Plain data, compiled into one shader.
4
+ *
5
+ * Modelled on the general material the Binbun packs ship
6
+ * (`shared/shader/transparent.gdshader`, their most-used shader):
7
+ *
8
+ * 1. up to three MASKS -- procedural noise, a gradient, a shape or an image,
9
+ * each scaled / scrolled / spun / optionally in polar UVs -- combined
10
+ * into one value m (0..1);
11
+ * 2. DISSOLVE d is taken off m: v = m - d;
12
+ * 3. alpha = smoothstep(threshold, threshold + softness, v);
13
+ * 4. the colour is the GRADIENT MAP `color` at v (a colour ramp indexed by
14
+ * the mask -- the white-hot core of a flame), optionally with a glowing
15
+ * EDGE where v is just above the threshold;
16
+ * 5. x `emission` (HDR) x the particle's own colour and alpha.
17
+ *
18
+ * Numbers marked `Animated` are a constant or `{ overLife: Curve }` --
19
+ * sampled at the particle's age. That is what Binbun's shaders do by reading
20
+ * the particle COLOR as data; here the file says what the number is for.
21
+ */
22
+ import * as T from 'three';
23
+ import { type Curve, type Gradient } from './document.js';
24
+ export type Animated = number | {
25
+ overLife: Curve;
26
+ };
27
+ /**
28
+ * Generated in the browser, tileable. `frequency` is cells across the tile.
29
+ * Godot's simplex maps to perlin (same look, a periodic version is simpler).
30
+ * cellular: distance to the nearest feature point (Voronoi blobs);
31
+ * cellEdges: F2 - F1 (bright cell walls).
32
+ */
33
+ export interface NoiseSource {
34
+ type: 'noise';
35
+ kind: 'perlin' | 'value' | 'cellular' | 'cellEdges';
36
+ fractal: 'none' | 'fbm' | 'ridged' | 'pingpong';
37
+ octaves: number;
38
+ frequency: number;
39
+ seed: number;
40
+ /** Domain warp: each sample is pushed by a second, smooth noise, by up to this many cells -- swirls and smears (Godot domain_warp). 0 = off. */
41
+ warp: number;
42
+ /** pingpong only: how many times the value folds back (Godot's fractal_ping_pong_strength, default 2). Higher = thinner strands. */
43
+ pingpong: number;
44
+ /** Texture side in pixels. */
45
+ size: 64 | 128 | 256 | 512;
46
+ }
47
+ export type MaskSource = NoiseSource
48
+ /**
49
+ * linear: 0 at the left edge to 1 at the right. radial: 1 at `center` to 0
50
+ * half a tile away. square: the same, square. band: a stripe across u,
51
+ * 1 at center.x falling to 0 `width` away (turn it with the mask's
52
+ * rotation; a shock ring's glowing stripe). `center` is in UVs, v up.
53
+ */
54
+ | {
55
+ type: 'gradient';
56
+ fill: 'linear' | 'radial' | 'square' | 'band';
57
+ center: [number, number];
58
+ width: number;
59
+ }
60
+ /** The part-1 particle shapes, plus a ring (`radius` and `width` as fractions of the half-size). */
61
+ | {
62
+ type: 'shape';
63
+ shape: 'dot' | 'glow' | 'star' | 'ring';
64
+ softness: number;
65
+ points: number;
66
+ sharpness: number;
67
+ radius: number;
68
+ width: number;
69
+ }
70
+ /** An image asset next to the effect. `channel` luma = brightness x alpha. */
71
+ | {
72
+ type: 'image';
73
+ texture: string;
74
+ channel: 'luma' | 'r' | 'a';
75
+ };
76
+ /** Binbun's twelve (`util/blend.gdshaderinc`), in its order. dodge is a / (1 - b); linearBurn a + b - 1. */
77
+ export declare const MASK_BLENDS: readonly ["add", "subtract", "multiply", "min", "max", "screen", "overlay", "hardLight", "softLight", "dodge", "burn", "linearBurn"];
78
+ export type MaskBlend = typeof MASK_BLENDS[number];
79
+ export interface Mask {
80
+ source: MaskSource;
81
+ /** UV repeats across the surface. */
82
+ scale: [number, number];
83
+ /** Tiles a second the texture moves: +u to the right, +v up (Godot's v scroll has the same sign; negate its u). */
84
+ scroll: [number, number];
85
+ /** Degrees a second, around the middle. */
86
+ spin: number;
87
+ /** A fixed turn of the texture, degrees around the middle (Binbun's uv alignment modes are 90-degree turns). */
88
+ rotation: number;
89
+ /** Map the UVs to (angle, distance from the middle): a scroll in v then flows outward. */
90
+ polar: boolean;
91
+ /** Each particle starts at its own place in the texture, so a crowd of particles is not identical. */
92
+ randomOffset: boolean;
93
+ invert: boolean;
94
+ /** Reshape the value with smoothstep(lo, hi, value) -- a soft threshold on this mask alone. null = as is. */
95
+ levels: [number, number] | null;
96
+ /**
97
+ * Added to this mask's value, then clamped to 0..1. Animate it over life
98
+ * with a linear gradient mask and `subtract` for a wipe that eats the
99
+ * particle from one side.
100
+ */
101
+ offset: Animated;
102
+ /** How this mask combines into the ones before it (ignored on the first). */
103
+ blend: MaskBlend;
104
+ strength: Animated;
105
+ }
106
+ export interface Material {
107
+ /** 0-3. None: the whole surface, solid (a mesh layer's default). */
108
+ masks: Mask[];
109
+ /** Taken off the mask value: 0 = whole, 1 = gone. Animate it over life to erode a particle away. */
110
+ dissolve: Animated;
111
+ /**
112
+ * alpha = ramp(threshold, threshold + softness, mask - dissolve) ^ power.
113
+ * `ramp` smooth is a smoothstep; linear a straight line (Binbun's
114
+ * transparent shader is linear with power 3).
115
+ */
116
+ threshold: Animated;
117
+ softness: number;
118
+ ramp: 'smooth' | 'linear';
119
+ power: number;
120
+ /** A glowing rim where the material is about to dissolve. width 0 = none. */
121
+ edge: {
122
+ width: number;
123
+ color: string;
124
+ emission: number;
125
+ };
126
+ /** The gradient map: the colour at each mask value (t = 0 the faint parts, 1 the strongest). */
127
+ color: Gradient;
128
+ opacity: Animated;
129
+ /** Brightness; above 1 is HDR. Multiplies the emitter's `intensity`. */
130
+ emission: Animated;
131
+ /** blend: soft alpha. cutout: opaque above `cutoff`, gone below (Godot's alpha scissor). dither: a stipple instead of transparency. */
132
+ alphaMode: 'blend' | 'cutout' | 'dither';
133
+ cutoff: number;
134
+ /**
135
+ * Meshes: fade by how squarely a surface faces the viewer (fresnel).
136
+ * edge keeps the silhouette and thins the middle (a shield, a bubble);
137
+ * center keeps the middle and fades the silhouette (a soft fireball).
138
+ * strength 0 = off. A camera-facing quad always faces the viewer, so it
139
+ * has no effect on flat particles.
140
+ */
141
+ rim: {
142
+ strength: number;
143
+ power: number;
144
+ mode: 'edge' | 'center';
145
+ };
146
+ /** Meshes: push each vertex along its normal by (mask 1 - offset) x amount -- lumpy smoke, a wobbling sphere. 0 = off; animate it to settle. */
147
+ displace: {
148
+ amount: Animated;
149
+ offset: number;
150
+ };
151
+ }
152
+ export declare const MATERIAL_LIMITS: {
153
+ readonly masks: 3;
154
+ readonly curves: 8;
155
+ };
156
+ export declare const ANIMATED_FIELDS: {
157
+ readonly dissolve: readonly [-1, 2];
158
+ readonly threshold: readonly [-1, 2];
159
+ readonly opacity: readonly [0, 1];
160
+ readonly emission: readonly [0, 32];
161
+ };
162
+ export declare function noiseDefaults(): NoiseSource;
163
+ export declare function maskDefaults(source?: MaskSource): Mask;
164
+ export declare function shapeSource(shape?: 'dot' | 'glow' | 'star' | 'ring'): MaskSource;
165
+ /** A soft round particle with a noise texture: a blank material that already reads as something. */
166
+ export declare function materialDefaults(): Material;
167
+ /** The value of an Animated number at life t (0..1). */
168
+ export declare function sampleAnimated(a: Animated, t: number): number;
169
+ /** Every image filename a material reads. */
170
+ export declare function materialTextures(m: Material): string[];
171
+ type Fail = (why: string) => never;
172
+ /**
173
+ * Fills omitted fields from the defaults, refuses unknown ones, checks
174
+ * ranges. `checkCurve` / `checkGradient` / `texturePattern` come from the
175
+ * document parser so the messages read the same.
176
+ */
177
+ export declare function parseMaterial(input: unknown, at: string, fail: Fail, h: {
178
+ checkCurve: (v: unknown, at: string) => void;
179
+ checkGradient: (v: unknown, at: string) => void;
180
+ texturePattern: RegExp;
181
+ }): Material;
182
+ /**
183
+ * The noise as `size * size` bytes, normalised to the full 0..255 range (as
184
+ * Godot's NoiseTexture2D does by default). Tileable: every octave is periodic
185
+ * in a whole number of cells. Deterministic per source.
186
+ */
187
+ export declare function generateNoise(n: NoiseSource): Uint8Array;
188
+ export declare function acquireNoiseTexture(n: NoiseSource): T.DataTexture;
189
+ export declare function releaseNoiseTexture(t: T.Texture): void;
190
+ /** For tests: how many distinct noise textures are alive. */
191
+ export declare function noiseTexturesAlive(): number;
192
+ /**
193
+ * A compiled material: the fragment-shader body for these features, the
194
+ * uniforms it reads, and what to free. The GLSL depends only on the
195
+ * material's STRUCTURE (which sources, blends, which numbers are curves), not
196
+ * its numbers, so editing a number never recompiles.
197
+ */
198
+ export interface CompiledMaterial {
199
+ /** Declarations + `vec4 vfxMaterial(vec2 uv, vec2 life)`. life = (t, random). */
200
+ code: string;
201
+ uniforms: Record<string, T.IUniform>;
202
+ /** Image filenames, by mask index, the caller binds into `uMask<i>`. */
203
+ images: Map<number, string>;
204
+ alphaMode: Material['alphaMode'];
205
+ /** The vertex shader pushes along the normal by `vfxDisplace(uv, life)` (defined in `code`). */
206
+ displace: boolean;
207
+ dispose(): void;
208
+ }
209
+ export declare function compileMaterial(m: Material): CompiledMaterial;
210
+ /**
211
+ * Starting points, so nobody begins from a blank material. Each is what one
212
+ * of the reference rebuilds needed (ADR-055), with the numbers rounded.
213
+ */
214
+ export declare const MATERIAL_PRESETS: Record<string, () => Material>;
215
+ export {};