@umicat/three-sdk 1.37.0 → 1.39.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.
package/README.md CHANGED
@@ -101,8 +101,26 @@ ramp, a gradient map for colour, an optional glowing edge, and HDR emission.
101
101
  `dissolve`, `threshold`, `opacity`, `emission` and each mask's `strength` /
102
102
  `offset` are a number or `{ overLife: Curve }`. See `src/vfx/material.ts`.
103
103
 
104
- **Write the lowest version.** `minimumVersion(doc)` is 3 only when a material
105
- is used; the editor and the agent write that, so an effect that needs nothing
104
+ **Meshes (version 4, 1.38.0, ADR-055 step 2).** `meshes: [...]` places Godot's
105
+ primitive meshes (quad, plane, sphere, cylinder/cone, torus, box, flat ring)
106
+ in the effect, each shown for a `start`/`life` window of the cycle with scale,
107
+ colour and alpha over that life and drawn with a material; `emitter.mesh`
108
+ draws every particle as such a mesh (`size` scales it; it stands on its
109
+ velocity with `align: velocity`). Materials gained rim (fresnel),
110
+ displacement, a cutout threshold and a band gradient; emitters gained
111
+ per-axis `sizeOverLifeXYZ`. Meshes draw before particles.
112
+
113
+ **Lights and scale (version 5, 1.39.0, ADR-055 step 3).** `lights: [...]`
114
+ (at most 2 point lights: position, colour, candela intensity, range, a
115
+ start/life window, intensity over life, flicker). They are created once and
116
+ dimmed to 0 when off, because adding or removing a three.js light recompiles
117
+ every lit material in the scene; `new VfxInstance(doc, { lights: false })` or
118
+ `effect.spawn({ lights: false })` builds none. An effect placed at a scale
119
+ scales everything: world-space particles take it in speed and size, and a
120
+ light's range follows it.
121
+
122
+ **Write the lowest version.** `minimumVersion(doc)` is 5 with lights, 4 with meshes, 3 with a
123
+ material, else 2; the editor and the agent write that, so an effect that needs nothing
106
124
  new stays version 2 and keeps playing on 1.36.
107
125
 
108
126
  ## What is proven, and by what
@@ -6,6 +6,12 @@ import { type VfxDocument, type Vec3 } from './document.js';
6
6
  export type VfxTextureSource = Map<string, T.Texture> | Record<string, T.Texture> | ((filename: string) => T.Texture | undefined);
7
7
  export interface VfxInstanceOptions {
8
8
  textures?: VfxTextureSource;
9
+ /**
10
+ * false: build no lights at all (an unlit or mobile-heavy game). Default
11
+ * true. Either way the number of lights never changes after construction,
12
+ * so a scene's lit materials never recompile because an effect played.
13
+ */
14
+ lights?: boolean;
9
15
  }
10
16
  /**
11
17
  * One playing copy of an effect. Shared by the VFX Editor and games: it owns
@@ -24,6 +30,8 @@ export declare class VfxInstance {
24
30
  private particleLayers;
25
31
  private byId;
26
32
  private flipbookLayers;
33
+ private meshLayers;
34
+ private lightLayers;
27
35
  private state;
28
36
  /** Particles born so far: hashed into each particle's `seed`. */
29
37
  private serial;
@@ -33,11 +41,16 @@ export declare class VfxInstance {
33
41
  private buildParticles;
34
42
  /** (Re)creates the per-instance buffers with room for `capacity` particles. */
35
43
  private allocate;
44
+ private buildMesh;
45
+ /** A mesh layer's or light's life fraction now, or -1 when it is not showing. */
46
+ private meshLife;
36
47
  private buildFlipbook;
37
48
  private random;
38
49
  /** Back to time 0 with the original seed: a replay is identical to the first play. */
39
50
  reset(): void;
40
51
  get particleCount(): number;
52
+ /** The point lights this instance made (empty with `{ lights: false }`). Never changes after construction. */
53
+ get lights(): readonly T.PointLight[];
41
54
  /** True once a NON-looping effect has stopped emitting, every particle has
42
55
  * died and every flipbook has played out -- the moment to `dispose()` a
43
56
  * one-shot. Always false for a looping effect. */
@@ -1,6 +1,10 @@
1
1
  import * as T from 'three';
2
2
  import { parseVfx, pickRange, sampleCurve, sampleGradient, LIMITS, } from './document.js';
3
- import { compileMaterial } from './material.js';
3
+ import { compileMaterial, materialDefaults } from './material.js';
4
+ import { meshGeometry, fixRingUv, meshLayerVertex, meshParticleVertex, meshFragment } from './mesh.js';
5
+ /** Closed shapes are drawn front-only, so an additive sphere does not show its back through its front. */
6
+ const closed = (s) => s.type === 'sphere' || s.type === 'box' || s.type === 'torus' || (s.type === 'cylinder' && s.caps);
7
+ const SIDE = { front: T.FrontSide, back: T.BackSide, both: T.DoubleSide };
4
8
  const SHARED_QUAD = (() => {
5
9
  // Corners in [0,1]^2 with y UP; the shader turns them into a cell-sized quad.
6
10
  const g = new T.BufferGeometry();
@@ -45,16 +49,16 @@ const PARTICLE_QUAD = (() => {
45
49
  })();
46
50
  // iMisc = (size, angle radians, frame, unused)
47
51
  const PARTICLE_VERTEX = `
48
- attribute vec3 iPos; attribute vec4 iColor; attribute vec4 iMisc; attribute vec3 iVel; attribute vec2 iLife;
52
+ attribute vec3 iPos; attribute vec4 iColor; attribute vec4 iMisc; attribute vec3 iVel; attribute vec2 iLife; attribute vec3 iAxes;
49
53
  uniform float uAlign; uniform float uStretch; uniform vec2 uCell; uniform mat3 uOrient; uniform vec3 uAxis;
50
54
  varying vec2 vUv; varying vec2 vQuad; varying vec4 vColor; varying vec2 vLife;
51
55
  void main(){
52
- vec2 c = position.xy;
53
- vQuad = c * 2.0;
56
+ vec2 c = position.xy * iAxes.xy; // per-axis scale over life; the UVs below stay on the unscaled corner
57
+ vQuad = position.xy * 2.0;
54
58
  vColor = iColor;
55
59
  vLife = iLife;
56
60
  float size = iMisc.x, angle = iMisc.y, frame = iMisc.z;
57
- vec2 uv = c + 0.5;
61
+ vec2 uv = position.xy + 0.5;
58
62
  vUv = vec2((mod(frame, uCell.x) + uv.x) / uCell.x, 1.0 - (floor(frame / uCell.x) + 1.0 - uv.y) / uCell.y);
59
63
  float s = sin(angle), co = cos(angle);
60
64
  vec2 turned = vec2(c.x * co - c.y * s, c.x * s + c.y * co) * size;
@@ -121,9 +125,9 @@ ${c.code}
121
125
  float vfxBayer(vec2 p){ ivec2 q = ivec2(mod(p, 4.0)); int i = q.x + q.y * 4;
122
126
  float m[16] = float[16](0.,8.,2.,10.,12.,4.,14.,6.,3.,11.,1.,9.,15.,7.,13.,5.); return (m[i] + 0.5) / 16.0; }
123
127
  void main(){
124
- vec4 m = vfxMaterial(vQuad * 0.5 + 0.5, vLife);
128
+ vec4 m = vfxMaterial(vQuad * 0.5 + 0.5, vLife, 1.0);
125
129
  float a = m.a * vColor.a;
126
- ${c.alphaMode === 'cutout' ? 'if (a < 0.5) discard; a = 1.0;' : c.alphaMode === 'dither' ? 'if (a < vfxBayer(gl_FragCoord.xy)) discard; a = 1.0;' : 'if (a <= 0.002) discard;'}
130
+ ${c.alphaMode === 'cutout' ? 'if (a < uCutoff) discard; a = 1.0;' : c.alphaMode === 'dither' ? 'if (a < vfxBayer(gl_FragCoord.xy)) discard; a = 1.0;' : 'if (a <= 0.002) discard;'}
127
131
  gl_FragColor = vec4(m.rgb * vColor.rgb, a);
128
132
  #include <tonemapping_fragment>
129
133
  #include <colorspace_fragment>
@@ -143,6 +147,7 @@ function resolveTexture(source, name) {
143
147
  const scratchColor = new T.Color();
144
148
  const scratchRgba = [0, 0, 0, 0];
145
149
  const scratchVec = new T.Vector3();
150
+ const scratchBasis = new T.Matrix3();
146
151
  /**
147
152
  * One playing copy of an effect. Shared by the VFX Editor and games: it owns
148
153
  * no renderer, no DOM and no animation loop -- add `root` to a scene and call
@@ -160,6 +165,8 @@ export class VfxInstance {
160
165
  this.particleLayers = [];
161
166
  this.byId = new Map();
162
167
  this.flipbookLayers = [];
168
+ this.meshLayers = [];
169
+ this.lightLayers = [];
163
170
  this.state = 1;
164
171
  /** Particles born so far: hashed into each particle's `seed`. */
165
172
  this.serial = 0;
@@ -176,32 +183,42 @@ export class VfxInstance {
176
183
  });
177
184
  for (const config of this.document.flipbooks ?? [])
178
185
  this.flipbookLayers.push(this.buildFlipbook(config, resolveTexture(options.textures, config.texture)));
186
+ (this.document.meshes ?? []).forEach((config, i) => this.meshLayers.push(this.buildMesh(config, i, (name) => resolveTexture(options.textures, name))));
187
+ if (options.lights !== false)
188
+ (this.document.lights ?? []).forEach((config, i) => {
189
+ // Created now and dimmed to 0 when off: never added or removed later.
190
+ const light = new T.PointLight(new T.Color(config.color), 0, config.range, 2);
191
+ light.name = config.id;
192
+ light.position.set(...config.position);
193
+ light.castShadow = false;
194
+ this.root.add(light);
195
+ this.lightLayers.push({ config, light, seed: seedOf(this.document.seed, 200000 + i) });
196
+ });
179
197
  this.draw();
180
198
  }
181
199
  buildParticles(config, index, root, textureOf) {
182
200
  const geometry = new T.InstancedBufferGeometry();
183
- geometry.index = PARTICLE_QUAD.index;
184
- geometry.setAttribute('position', PARTICLE_QUAD.getAttribute('position'));
185
- const look = config.look;
186
- const texture = look.type === 'texture' || look.type === 'sheet' ? textureOf(look.texture) : undefined;
187
- const images = look.type === 'texture' || look.type === 'sheet' ? [texture] : [];
188
- const compiled = look.type === 'material' ? compileMaterial(look.material) : undefined;
201
+ const look = config.look, solid = config.mesh;
202
+ if (solid) {
203
+ // A mesh particle: the shape's own buffers, instanced.
204
+ const g = fixRingUv(meshGeometry(solid), solid);
205
+ geometry.index = g.index;
206
+ for (const k of ['position', 'normal', 'uv'])
207
+ geometry.setAttribute(k, g.getAttribute(k));
208
+ }
209
+ else {
210
+ geometry.index = PARTICLE_QUAD.index;
211
+ geometry.setAttribute('position', PARTICLE_QUAD.getAttribute('position'));
212
+ }
213
+ const texture = !solid && (look.type === 'texture' || look.type === 'sheet') ? textureOf(look.texture) : undefined;
214
+ const images = texture || (!solid && (look.type === 'texture' || look.type === 'sheet')) ? [texture] : [];
215
+ // A mesh particle always draws through a material: its look's, or a solid one.
216
+ const compiled = look.type === 'material' ? compileMaterial(look.material) : solid ? compileMaterial({ ...materialDefaults(), masks: [] }) : undefined;
189
217
  const repeats = [];
190
218
  if (compiled)
191
- for (const [i, name] of compiled.images) {
192
- const t = textureOf(name);
193
- images.push(t);
194
- if (!t) {
195
- compiled.uniforms[`uMask${i}`].value = null;
196
- continue;
197
- }
198
- const copy = t.clone();
199
- copy.wrapS = copy.wrapT = T.RepeatWrapping;
200
- repeats.push({ source: t, copy, version: -1 });
201
- compiled.uniforms[`uMask${i}`].value = copy;
202
- }
219
+ bindImages(compiled, textureOf, images, repeats);
203
220
  const material = new T.ShaderMaterial({
204
- transparent: true, depthWrite: false, side: T.DoubleSide,
221
+ transparent: true, depthWrite: false, side: solid && closed(solid) ? T.FrontSide : T.DoubleSide,
205
222
  blending: config.blend === 'additive' ? T.AdditiveBlending : T.NormalBlending,
206
223
  uniforms: {
207
224
  uLook: { value: LOOK_CODE[look.type] }, uSoft: { value: look.type === 'dot' ? look.softness : 0 },
@@ -212,7 +229,8 @@ export class VfxInstance {
212
229
  uOrient: { value: new T.Matrix3().setFromMatrix4(new T.Matrix4().makeRotationFromQuaternion(emitterQuaternion(config))) },
213
230
  ...compiled?.uniforms,
214
231
  },
215
- vertexShader: PARTICLE_VERTEX, fragmentShader: compiled ? materialFragment(compiled) : PARTICLE_FRAGMENT,
232
+ vertexShader: solid ? meshParticleVertex(compiled) : PARTICLE_VERTEX,
233
+ fragmentShader: solid ? meshFragment(compiled) : compiled ? materialFragment(compiled) : PARTICLE_FRAGMENT,
216
234
  });
217
235
  const mesh = new T.Mesh(geometry, material);
218
236
  mesh.frustumCulled = false;
@@ -232,15 +250,56 @@ export class VfxInstance {
232
250
  /** (Re)creates the per-instance buffers with room for `capacity` particles. */
233
251
  allocate(layer, capacity) {
234
252
  const make = (size) => new T.InstancedBufferAttribute(new Float32Array(capacity * size), size).setUsage(T.DynamicDrawUsage);
235
- layer.attributes = { pos: make(3), color: make(4), misc: make(4), vel: make(3), life: make(2) };
253
+ layer.attributes = { pos: make(3), color: make(4), misc: make(4), vel: make(3), life: make(2), axes: make(3) };
236
254
  const g = layer.geometry;
237
255
  g.setAttribute('iPos', layer.attributes.pos);
238
256
  g.setAttribute('iColor', layer.attributes.color);
239
257
  g.setAttribute('iMisc', layer.attributes.misc);
240
258
  g.setAttribute('iVel', layer.attributes.vel);
241
259
  g.setAttribute('iLife', layer.attributes.life);
260
+ g.setAttribute('iAxes', layer.attributes.axes);
242
261
  layer.capacity = capacity;
243
262
  }
263
+ buildMesh(config, index, textureOf) {
264
+ const geometry = fixRingUv(meshGeometry(config.shape), config.shape);
265
+ const compiled = compileMaterial(config.material);
266
+ const images = [], repeats = [];
267
+ bindImages(compiled, textureOf, images, repeats);
268
+ const s = config.shape;
269
+ const material = new T.ShaderMaterial({
270
+ transparent: true, depthWrite: false,
271
+ side: config.side === 'both' && closed(s) ? T.FrontSide : SIDE[config.side],
272
+ blending: config.blend === 'additive' ? T.AdditiveBlending : T.NormalBlending,
273
+ uniforms: {
274
+ uLayerColor: { value: new T.Vector4(1, 1, 1, 1) }, uLayerLife: { value: new T.Vector2(0, 0) },
275
+ uFacing: { value: config.facing === 'camera' ? (s.type === 'quad' ? 1 : s.type === 'plane' ? 2 : 0) : 0 },
276
+ ...compiled.uniforms,
277
+ },
278
+ vertexShader: meshLayerVertex(compiled), fragmentShader: meshFragment(compiled),
279
+ });
280
+ const mesh = new T.Mesh(geometry, material);
281
+ // Meshes draw BEFORE particles: an effect's meshes are its core, its ground rings and discs, which particles fly in front of.
282
+ mesh.name = config.id;
283
+ mesh.frustumCulled = false;
284
+ mesh.renderOrder = -100 + index;
285
+ mesh.visible = false;
286
+ mesh.position.set(...config.position);
287
+ mesh.rotation.set(config.rotation[0] * DEG, config.rotation[1] * DEG, config.rotation[2] * DEG, 'XYZ');
288
+ this.root.add(mesh);
289
+ return { config, mesh, geometry, material, compiled, images, repeats, seed: seedOf(this.document.seed, 100000 + index) };
290
+ }
291
+ /** A mesh layer's or light's life fraction now, or -1 when it is not showing. */
292
+ meshLife(c) {
293
+ if (!c.enabled)
294
+ return -1;
295
+ const d = this.document.duration, life = c.life ?? Math.max(.01, d - c.start);
296
+ const cycleTime = this.document.loop ? this.time % d : this.time;
297
+ let t = (cycleTime - c.start) / life;
298
+ // A looping layer that outlives its cycle carries over into the next one.
299
+ if (this.document.loop && t < 0 && this.time >= d)
300
+ t = (cycleTime + d - c.start) / life;
301
+ return t >= 0 && t < 1 ? t : -1;
302
+ }
244
303
  buildFlipbook(config, texture) {
245
304
  const material = new T.ShaderMaterial({
246
305
  transparent: true, depthWrite: false, side: T.DoubleSide,
@@ -278,13 +337,17 @@ export class VfxInstance {
278
337
  this.draw();
279
338
  }
280
339
  get particleCount() { return this.live; }
340
+ /** The point lights this instance made (empty with `{ lights: false }`). Never changes after construction. */
341
+ get lights() { return this.lightLayers.map((l) => l.light); }
281
342
  /** True once a NON-looping effect has stopped emitting, every particle has
282
343
  * died and every flipbook has played out -- the moment to `dispose()` a
283
344
  * one-shot. Always false for a looping effect. */
284
345
  get finished() {
285
346
  if (this.document.loop || this.time < this.document.duration)
286
347
  return false;
287
- return this.live === 0 && this.flipbookLayers.every((f) => f.done);
348
+ const over = (c) => !c.enabled || this.time >= c.start + (c.life ?? Math.max(.01, this.document.duration - c.start));
349
+ const meshesDone = this.meshLayers.every(({ config }) => over(config)) && this.lightLayers.every(({ config }) => over(config));
350
+ return this.live === 0 && meshesDone && this.flipbookLayers.every((f) => f.done);
288
351
  }
289
352
  /** Kept for 1.35 callers. Particles are world-sized quads now, so the viewport no longer matters. */
290
353
  setViewportHeight(_height) { }
@@ -473,7 +536,8 @@ export class VfxInstance {
473
536
  x = p.x;
474
537
  y = p.y;
475
538
  z = p.z;
476
- const v = scratchVec.set(vx, vy, vz).transformDirection(m).multiplyScalar(Math.hypot(vx, vy, vz));
539
+ // The linear part, scale included: an effect placed at 2x throws its particles twice as fast (Godot's emission transform).
540
+ const v = scratchVec.set(vx, vy, vz).applyMatrix3(scratchBasis.setFromMatrix4(m));
477
541
  vx = v.x;
478
542
  vy = v.y;
479
543
  vz = v.z;
@@ -484,6 +548,7 @@ export class VfxInstance {
484
548
  angle: pickRange(c.angle, r()) * DEG, spin: pickRange(c.spin, r()) * DEG, size: pickRange(c.size, r()),
485
549
  r: scratchRgba[0], g: scratchRgba[1], b: scratchRgba[2], a: scratchRgba[3],
486
550
  seed: seedOf(this.document.seed, this.serial++),
551
+ scale: c.space === 'world' ? this.root.matrixWorld.getMaxScaleOnAxis() : 1,
487
552
  radialSpeed: pickRange(c.radialSpeed, r()), radialAccel: pickRange(c.radialAccel, r()),
488
553
  tangentialAccel: pickRange(c.tangentialAccel, r()), orbit: pickRange(c.orbit, r()), damping: pickRange(c.damping, r()),
489
554
  owed: c.children.map(() => 0),
@@ -551,8 +616,9 @@ export class VfxInstance {
551
616
  const c = l.config, n = l.particles.length;
552
617
  if (n > l.capacity)
553
618
  this.allocate(l, Math.min(LIMITS.particles, Math.max(n, l.capacity * 2)));
554
- const { pos, color, misc, vel, life } = l.attributes;
555
- const P = pos.array, C = color.array, M = misc.array, V = vel.array, L = life.array;
619
+ const { pos, color, misc, vel, life, axes } = l.attributes;
620
+ const P = pos.array, C = color.array, M = misc.array, V = vel.array, L = life.array, A = axes.array;
621
+ const xyz = c.sizeOverLifeXYZ;
556
622
  const look = c.look;
557
623
  for (let i = 0; i < n; i++) {
558
624
  const p = l.particles[i], t = p.age / p.life;
@@ -577,29 +643,67 @@ export class VfxInstance {
577
643
  C[i * 4 + 1] = scratchColor.g * c.intensity;
578
644
  C[i * 4 + 2] = scratchColor.b * c.intensity;
579
645
  C[i * 4 + 3] = Math.min(1, a);
580
- M[i * 4] = p.size * (c.sizeOverLife ? Math.max(0, sampleCurve(c.sizeOverLife, t)) : 1);
646
+ M[i * 4] = p.size * p.scale * (c.sizeOverLife ? Math.max(0, sampleCurve(c.sizeOverLife, t)) : 1);
581
647
  M[i * 4 + 1] = p.angle;
582
648
  L[i * 2] = t;
583
649
  L[i * 2 + 1] = p.seed;
650
+ A[i * 3] = xyz?.x ? sampleCurve(xyz.x, t) : 1;
651
+ A[i * 3 + 1] = xyz?.y ? sampleCurve(xyz.y, t) : 1;
652
+ A[i * 3 + 2] = xyz?.z ? sampleCurve(xyz.z, t) : 1;
584
653
  M[i * 4 + 2] = look.type !== 'sheet' ? 0 : look.fps === 'life' ? Math.min(look.frames - 1, Math.floor(t * look.frames)) : Math.floor(p.age * look.fps) % look.frames;
585
654
  }
586
655
  l.geometry.instanceCount = n;
587
- for (const attribute of [pos, color, misc, vel, life])
656
+ for (const attribute of [pos, color, misc, vel, life, axes])
588
657
  attribute.needsUpdate = true;
589
658
  if (l.compiled)
590
659
  l.compiled.uniforms.uTime.value = this.time;
591
- // A copy made before its image decoded never uploads on its own: follow the source's version.
592
- for (const r of l.repeats)
593
- if (r.version !== r.source.version && r.source.image?.width) {
594
- r.copy.image = r.source.image;
595
- r.copy.needsUpdate = true;
596
- r.version = r.source.version;
597
- }
660
+ syncRepeats(l.repeats);
598
661
  // A textured look waits for its images; a missing one draws nothing.
599
662
  l.mesh.visible = n > 0 && l.images.every((t) => !!t?.image?.width);
600
663
  if (c.space === 'world')
601
664
  l.mesh.matrix.copy(this.root.matrixWorld).invert();
602
665
  }
666
+ if (this.lightLayers.length) {
667
+ this.root.updateWorldMatrix(true, false);
668
+ const k = this.root.matrixWorld.getMaxScaleOnAxis();
669
+ for (const l of this.lightLayers) {
670
+ const c = l.config, t = this.meshLife(c);
671
+ let power = t < 0 ? 0 : c.intensity * (c.intensityOverLife ? Math.max(0, sampleCurve(c.intensityOverLife, t)) : 1);
672
+ if (power > 0 && c.flicker > 0) {
673
+ // Three incommensurate sines: steady-looking randomness, the same on every replay.
674
+ const x = this.time + l.seed * 17, n = Math.sin(x * 23.1) * .5 + Math.sin(x * 37.7) * .3 + Math.sin(x * 61.3) * .2;
675
+ power *= 1 - c.flicker * .5 * (1 + n);
676
+ }
677
+ l.light.intensity = power;
678
+ // A bigger effect lights further.
679
+ l.light.distance = c.range * k;
680
+ }
681
+ }
682
+ for (const m of this.meshLayers) {
683
+ const c = m.config, t = this.meshLife(c);
684
+ const ready = m.images.every((x) => !!x?.image?.width);
685
+ m.mesh.visible = t >= 0 && ready;
686
+ if (!m.mesh.visible)
687
+ continue;
688
+ const k = c.scaleOverLife ? sampleCurve(c.scaleOverLife, t) : 1;
689
+ m.mesh.scale.set(c.scale[0] * k, c.scale[1] * k, c.scale[2] * k);
690
+ sampleGradient({ stops: [[0, c.color, 1]] }, 0, scratchRgba);
691
+ let [r, g, b] = scratchRgba, a = 1;
692
+ if (c.colorOverLife) {
693
+ sampleGradient(c.colorOverLife, t, scratchRgba);
694
+ r *= scratchRgba[0];
695
+ g *= scratchRgba[1];
696
+ b *= scratchRgba[2];
697
+ a *= scratchRgba[3];
698
+ }
699
+ if (c.alphaOverLife)
700
+ a *= Math.max(0, sampleCurve(c.alphaOverLife, t));
701
+ scratchColor.setRGB(r, g, b, T.SRGBColorSpace);
702
+ m.material.uniforms.uLayerColor.value.set(scratchColor.r * c.intensity, scratchColor.g * c.intensity, scratchColor.b * c.intensity, Math.min(1, a));
703
+ m.material.uniforms.uLayerLife.value.set(t, m.seed);
704
+ m.compiled.uniforms.uTime.value = this.time;
705
+ syncRepeats(m.repeats);
706
+ }
603
707
  for (const f of this.flipbookLayers) {
604
708
  const frame = this.frameOf(f.config);
605
709
  if (frame < 0 && this.time >= f.config.delay)
@@ -631,14 +735,52 @@ export class VfxInstance {
631
735
  }
632
736
  for (const f of this.flipbookLayers)
633
737
  f.material.dispose();
738
+ for (const m of this.meshLayers) {
739
+ m.geometry.dispose();
740
+ m.material.dispose();
741
+ m.compiled.dispose();
742
+ for (const r of m.repeats)
743
+ r.copy.dispose();
744
+ }
745
+ for (const l of this.lightLayers)
746
+ l.light.dispose();
634
747
  this.particleLayers = [];
635
748
  this.flipbookLayers = [];
749
+ this.meshLayers = [];
750
+ this.lightLayers = [];
636
751
  this.byId.clear();
637
752
  this.live = 0;
638
753
  this.root.removeFromParent();
639
754
  this.root.clear();
640
755
  }
641
756
  }
757
+ /**
758
+ * Bind a material's image masks. The shared texture is clamped for sprite
759
+ * sheets, so a mask gets a repeat-wrapped copy of it (same decoded image).
760
+ */
761
+ function bindImages(compiled, textureOf, images, repeats) {
762
+ for (const [i, name] of compiled.images) {
763
+ const t = textureOf(name);
764
+ images.push(t);
765
+ if (!t) {
766
+ compiled.uniforms[`uMask${i}`].value = null;
767
+ continue;
768
+ }
769
+ const copy = t.clone();
770
+ copy.wrapS = copy.wrapT = T.RepeatWrapping;
771
+ repeats.push({ source: t, copy, version: -1 });
772
+ compiled.uniforms[`uMask${i}`].value = copy;
773
+ }
774
+ }
775
+ /** A copy made before its image decoded never uploads on its own: follow the source's version. */
776
+ function syncRepeats(repeats) {
777
+ for (const r of repeats)
778
+ if (r.version !== r.source.version && r.source.image?.width) {
779
+ r.copy.image = r.source.image;
780
+ r.copy.needsUpdate = true;
781
+ r.version = r.source.version;
782
+ }
783
+ }
642
784
  /** A particle's material seed, 0..1, from the effect seed and its birth order. */
643
785
  function seedOf(seed, serial) {
644
786
  let h = Math.imul(serial + 1, 0x9e3779b1) ^ Math.imul(seed, 0x85ebca6b);
@@ -15,11 +15,18 @@
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
17
  *
18
+ * Version 5 (1.39) adds LIGHTS (`lights`, point lights, ADR-055 step 3).
19
+ *
20
+ * Version 4 (1.38) adds MESHES: mesh layers (`meshes`) and mesh-shaped
21
+ * particles (`emitter.mesh`), ADR-055 step 2. A 1.37 reader ignores unknown
22
+ * top-level fields, so meshes needed their own version to fail loudly there.
23
+ *
18
24
  * Version 3 (1.37) adds the effect MATERIAL (`look: { type: 'material' }`,
19
25
  * ADR-055). A document that uses none of it is still written as version 2 --
20
26
  * `minimumVersion()` -- so games whose lockfile holds 1.36 keep playing it.
21
27
  */
22
28
  import { type Material } from './material.js';
29
+ import { type MeshShape, type MeshLayer } from './mesh.js';
23
30
  /** A number, or `[min, max]`: picked uniformly per particle. */
24
31
  export type Range = number | [number, number];
25
32
  export type Vec3 = [number, number, number];
@@ -160,6 +167,16 @@ export interface Emitter {
160
167
  /** World width of one particle. */
161
168
  size: Range;
162
169
  sizeOverLife?: Curve;
170
+ /**
171
+ * (version 4) Per-axis scale over life on top of `size` (Godot's
172
+ * CurveXYZTexture scale curve): a shock ring that widens without getting
173
+ * taller. A quad uses x (width) and y (height). A missing axis stays 1.
174
+ */
175
+ sizeOverLifeXYZ?: {
176
+ x?: Curve;
177
+ y?: Curve;
178
+ z?: Curve;
179
+ };
163
180
  /** One stop: that colour. More: each particle picks a point on it at random. */
164
181
  color: Gradient;
165
182
  /** Multiplies `color` over life. */
@@ -180,6 +197,13 @@ export interface Emitter {
180
197
  stretch: number;
181
198
  blend: 'normal' | 'additive';
182
199
  children: SubEmitter[];
200
+ /**
201
+ * (version 3) Draw each particle as this mesh instead of a camera-facing
202
+ * quad: `size` then SCALES the mesh. It stands on the emitter's up, or on
203
+ * its velocity / the emitter axis with align velocity / axis, turned by
204
+ * `angle` about that line.
205
+ */
206
+ mesh?: MeshShape;
183
207
  }
184
208
  export interface Flipbook {
185
209
  id: string;
@@ -207,7 +231,7 @@ export interface Flipbook {
207
231
  blend: 'normal' | 'additive';
208
232
  }
209
233
  export interface VfxDocument {
210
- version: 2 | 3;
234
+ version: 2 | 3 | 4 | 5;
211
235
  name: string;
212
236
  seed: number;
213
237
  /** Seconds in one cycle. A looping effect repeats it; a one-shot stops emitting after it. */
@@ -216,6 +240,31 @@ export interface VfxDocument {
216
240
  humanCurated: boolean;
217
241
  emitters: Emitter[];
218
242
  flipbooks?: Flipbook[];
243
+ /** (version 4) Meshes with a material: a shockwave ring, a fireball sphere, a ground disc. */
244
+ meshes?: MeshLayer[];
245
+ /** (version 5) Point lights: the flash of a muzzle, the glow a fire throws on the ground. At most 2. */
246
+ lights?: LightLayer[];
247
+ }
248
+ /**
249
+ * A point light, created once with the effect and dimmed to 0 when it is off
250
+ * -- adding or removing a light in three.js recompiles every lit material in
251
+ * the scene, which would stall a game on every shot. `intensity` is three.js
252
+ * candela with physical (inverse-square) falloff, cut off at `range`.
253
+ */
254
+ export interface LightLayer {
255
+ id: string;
256
+ enabled: boolean;
257
+ position: Vec3;
258
+ color: string;
259
+ intensity: number;
260
+ range: number;
261
+ /** Seconds into each cycle it comes on, and for how long (null: to the end of the cycle). */
262
+ start: number;
263
+ life: number | null;
264
+ /** Over the light's own life; multiplies `intensity`. */
265
+ intensityOverLife?: Curve;
266
+ /** 0-1: how much it flickers (a fire); 0 = steady. */
267
+ flicker: number;
219
268
  }
220
269
  /** A version-1 emitter: a disc firing upward with linear colour/size/alpha. Read, never written. */
221
270
  export interface EmitterV1 {
@@ -236,6 +285,8 @@ export interface EmitterV1 {
236
285
  export declare const LIMITS: {
237
286
  readonly emitters: 8;
238
287
  readonly layers: 8;
288
+ readonly meshes: 8;
289
+ readonly lights: 2;
239
290
  readonly particles: 4000;
240
291
  readonly cells: 4096;
241
292
  readonly bursts: 16;
@@ -325,7 +376,13 @@ export declare function parseVfx(value: unknown): VfxDocument;
325
376
  * emitter uses the material look, else 2. The editor and the agent write
326
377
  * this, so an effect that needs nothing new still plays on 1.36.
327
378
  */
328
- export declare function minimumVersion(d: Pick<VfxDocument, 'emitters'>): 2 | 3;
379
+ export declare function minimumVersion(d: Pick<VfxDocument, 'emitters' | 'meshes' | 'lights'>): 2 | 3 | 4 | 5;
380
+ /** A new mesh layer: a soft additive ring on the ground, for the editor's "Add" and the agent. */
381
+ export declare function meshLayerDefaults(): Omit<MeshLayer, 'id'>;
382
+ /** A new light: a warm glow just above the origin, lit for the whole cycle. */
383
+ export declare function lightLayerDefaults(): Omit<LightLayer, 'id'>;
384
+ export declare function lightLayer(id: string, patch?: Partial<LightLayer>): LightLayer;
385
+ export declare function meshLayer(id: string, patch?: Partial<MeshLayer>): MeshLayer;
329
386
  /**
330
387
  * The most particles an effect can have alive at once, estimated: per enabled
331
388
  * emitter, rate x longest life plus every burst, and for sub-emitters, the
@@ -15,12 +15,19 @@
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
17
  *
18
+ * Version 5 (1.39) adds LIGHTS (`lights`, point lights, ADR-055 step 3).
19
+ *
20
+ * Version 4 (1.38) adds MESHES: mesh layers (`meshes`) and mesh-shaped
21
+ * particles (`emitter.mesh`), ADR-055 step 2. A 1.37 reader ignores unknown
22
+ * top-level fields, so meshes needed their own version to fail loudly there.
23
+ *
18
24
  * Version 3 (1.37) adds the effect MATERIAL (`look: { type: 'material' }`,
19
25
  * ADR-055). A document that uses none of it is still written as version 2 --
20
26
  * `minimumVersion()` -- so games whose lockfile holds 1.36 keep playing it.
21
27
  */
22
- import { parseMaterial, materialTextures } from './material.js';
23
- export const LIMITS = { emitters: 8, layers: 8, particles: 4000, cells: 4096, bursts: 16, children: 4, curvePoints: 8, gradientStops: 16 };
28
+ import { parseMaterial, materialTextures, materialDefaults } from './material.js';
29
+ import { parseMeshShape } from './mesh.js';
30
+ export const LIMITS = { emitters: 8, layers: 8, meshes: 8, lights: 2, particles: 4000, cells: 4096, bursts: 16, children: 4, curvePoints: 8, gradientStops: 16 };
24
31
  /** Every emitter field's value when a document leaves it out. */
25
32
  export function emitterDefaults() {
26
33
  return {
@@ -99,6 +106,8 @@ export function vfxTextures(document) {
99
106
  else if (e.look.type === 'material')
100
107
  names.push(...materialTextures(e.look.material));
101
108
  }
109
+ for (const m of document.meshes ?? [])
110
+ names.push(...materialTextures(m.material));
102
111
  return [...new Set(names)];
103
112
  }
104
113
  // ---------------------------------------------------------------- sampling
@@ -175,8 +184,8 @@ export function parseVfx(value) {
175
184
  const d = structuredClone(value);
176
185
  const number = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
177
186
  const color = (v) => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v);
178
- if (d.version !== 2 && d.version !== 3)
179
- fail(`version must be 2 or 3 (or 1, which is upgraded)${typeof d.version === 'number' && d.version > 3 ? ` -- version ${d.version} was written by a newer editor: update @umicat/three-sdk` : ''}`);
187
+ if (![2, 3, 4, 5].includes(d.version))
188
+ fail(`version must be 2, 3, 4 or 5 (or 1, which is upgraded)${typeof d.version === 'number' && d.version > 5 ? ` -- version ${d.version} was written by a newer editor: update @umicat/three-sdk` : ''}`);
180
189
  if (typeof d.name !== 'string' || !d.name.trim() || d.name.length > 80)
181
190
  fail('name must be 1-80 characters');
182
191
  if (!number(d.seed, 1, 2147483646) || !Number.isInteger(d.seed))
@@ -192,8 +201,12 @@ export function parseVfx(value) {
192
201
  if (d.flipbooks !== undefined && !Array.isArray(d.flipbooks))
193
202
  fail('flipbooks must be a list');
194
203
  const flipbooks = d.flipbooks ?? [];
204
+ if (d.meshes !== undefined && (!Array.isArray(d.meshes) || d.meshes.length > LIMITS.meshes))
205
+ fail(`meshes must be a list of 0-${LIMITS.meshes}`);
206
+ if (d.meshes !== undefined && d.version < 4)
207
+ fail('meshes are version 4: set "version": 4 (needs @umicat/three-sdk 1.38 or later)');
195
208
  const layers = d.emitters.length + flipbooks.length;
196
- if (layers < 1 || layers > LIMITS.layers)
209
+ if (layers > LIMITS.layers || layers + (d.meshes?.length ?? 0) < 1)
197
210
  fail(`an effect needs 1-${LIMITS.layers} layers (emitters + flipbooks), it has ${layers}`);
198
211
  const ids = new Set();
199
212
  const checkId = (id, at) => {
@@ -245,7 +258,7 @@ export function parseVfx(value) {
245
258
  fail(`${at} is not an object`);
246
259
  checkId(input.id, at);
247
260
  emitterIds.add(input.id);
248
- const known = new Set(['id', ...Object.keys(emitterDefaults()), ...CURVE_FIELDS, 'colorOverLife']);
261
+ const known = new Set(['id', ...Object.keys(emitterDefaults()), ...CURVE_FIELDS, 'colorOverLife', 'mesh', 'sizeOverLifeXYZ']);
249
262
  for (const key of Object.keys(input))
250
263
  if (!known.has(key))
251
264
  fail(`${at}.${key} is not an emitter field (a version-1 field? set "version": 1, or see emitterDefaults())`);
@@ -342,6 +355,23 @@ export function parseVfx(value) {
342
355
  fail(`${lat}.type must be dot, glow, star, texture, sheet or material`);
343
356
  if (!['camera', 'velocity', 'ground', 'axis'].includes(e.align))
344
357
  fail(`${at}.align must be "camera", "velocity", "ground" or "axis"`);
358
+ if (e.sizeOverLifeXYZ !== undefined) {
359
+ if (d.version < 4)
360
+ fail(`${at}.sizeOverLifeXYZ is version 4: set "version": 4 (needs @umicat/three-sdk 1.38 or later)`);
361
+ const xyz = e.sizeOverLifeXYZ;
362
+ if (!xyz || typeof xyz !== 'object' || Array.isArray(xyz))
363
+ fail(`${at}.sizeOverLifeXYZ must be { x?, y?, z? } curves`);
364
+ for (const k of Object.keys(xyz)) {
365
+ if (!['x', 'y', 'z'].includes(k))
366
+ fail(`${at}.sizeOverLifeXYZ.${k} is not an axis (x, y, z)`);
367
+ checkCurve(xyz[k], `${at}.sizeOverLifeXYZ.${k}`);
368
+ }
369
+ }
370
+ if (e.mesh !== undefined) {
371
+ if (d.version < 4)
372
+ fail(`${at}.mesh is version 4: set "version": 4 (needs @umicat/three-sdk 1.38 or later)`);
373
+ e.mesh = parseMeshShape(e.mesh, `${at}.mesh`, fail);
374
+ }
345
375
  if (!['normal', 'additive'].includes(e.blend))
346
376
  fail(`${at}.blend must be "normal" or "additive"`);
347
377
  if (!Array.isArray(e.children) || e.children.length > LIMITS.children)
@@ -382,6 +412,80 @@ export function parseVfx(value) {
382
412
  const budget = particleBudget(d);
383
413
  if (budget > LIMITS.particles)
384
414
  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}`);
415
+ if (d.lights !== undefined) {
416
+ if (!Array.isArray(d.lights) || d.lights.length > LIMITS.lights)
417
+ fail(`lights must be a list of 0-${LIMITS.lights}`);
418
+ if (d.version < 5)
419
+ fail('lights are version 5: set "version": 5 (needs @umicat/three-sdk 1.39 or later)');
420
+ d.lights = d.lights.map((raw, i) => {
421
+ const at = `lights[${i}]`;
422
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
423
+ fail(`${at} is not an object`);
424
+ checkId(raw.id, at);
425
+ const base = lightLayerDefaults();
426
+ for (const k of Object.keys(raw))
427
+ if (!(k in base) && k !== 'id' && k !== 'intensityOverLife')
428
+ fail(`${at}.${k} is not a light field (expected id, ${Object.keys(base).join(', ')}, intensityOverLife)`);
429
+ const l = { ...base, ...raw };
430
+ if (typeof l.enabled !== 'boolean')
431
+ fail(`${at}.enabled must be a boolean`);
432
+ checkVec(l.position, `${at}.position`, -100, 100);
433
+ if (!color(l.color))
434
+ fail(`${at}.color must be #rrggbb`);
435
+ if (!number(l.intensity, 0, 1000))
436
+ fail(`${at}.intensity must be 0-1000 (candela)`);
437
+ if (!number(l.range, .1, 100))
438
+ fail(`${at}.range must be 0.1-100`);
439
+ if (!number(l.start, 0, 60))
440
+ fail(`${at}.start must be 0-60`);
441
+ if (l.life !== null && !number(l.life, .01, 60))
442
+ fail(`${at}.life must be null (to the end of the cycle) or 0.01-60`);
443
+ if (l.intensityOverLife !== undefined)
444
+ checkCurve(l.intensityOverLife, `${at}.intensityOverLife`);
445
+ if (!number(l.flicker, 0, 1))
446
+ fail(`${at}.flicker must be 0-1`);
447
+ return l;
448
+ });
449
+ }
450
+ if (d.meshes)
451
+ d.meshes = d.meshes.map((raw, i) => {
452
+ const at = `meshes[${i}]`;
453
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
454
+ fail(`${at} is not an object`);
455
+ checkId(raw.id, at);
456
+ const base = meshLayerDefaults();
457
+ for (const k of Object.keys(raw))
458
+ if (!(k in base) && !['id', 'scaleOverLife', 'colorOverLife', 'alphaOverLife'].includes(k))
459
+ fail(`${at}.${k} is not a mesh-layer field (expected id, ${Object.keys(base).join(', ')}, scaleOverLife, colorOverLife, alphaOverLife)`);
460
+ const m = { ...base, ...raw };
461
+ if (typeof m.enabled !== 'boolean')
462
+ fail(`${at}.enabled must be a boolean`);
463
+ m.shape = parseMeshShape(m.shape, `${at}.shape`, fail);
464
+ checkVec(m.position, `${at}.position`, -100, 100);
465
+ checkVec(m.rotation, `${at}.rotation`, -360, 360);
466
+ checkVec(m.scale, `${at}.scale`, -100, 100);
467
+ if (m.facing !== 'none' && m.facing !== 'camera')
468
+ fail(`${at}.facing must be "none" or "camera"`);
469
+ if (!number(m.start, 0, 60))
470
+ fail(`${at}.start must be 0-60`);
471
+ if (m.life !== null && !number(m.life, .01, 60))
472
+ fail(`${at}.life must be null (to the end of the cycle) or 0.01-60`);
473
+ for (const k of ['scaleOverLife', 'alphaOverLife'])
474
+ if (m[k] !== undefined)
475
+ checkCurve(m[k], `${at}.${k}`);
476
+ if (!color(m.color))
477
+ fail(`${at}.color must be #rrggbb`);
478
+ if (m.colorOverLife !== undefined)
479
+ checkGradient(m.colorOverLife, `${at}.colorOverLife`);
480
+ if (!number(m.intensity, 0, 16))
481
+ fail(`${at}.intensity must be 0-16`);
482
+ if (m.blend !== 'normal' && m.blend !== 'additive')
483
+ fail(`${at}.blend must be "normal" or "additive"`);
484
+ if (!['front', 'back', 'both'].includes(m.side))
485
+ fail(`${at}.side must be "front", "back" or "both"`);
486
+ m.material = parseMaterial(m.material, `${at}.material`, fail, { checkCurve, checkGradient, texturePattern: TEXTURE_PATTERN });
487
+ return m;
488
+ });
385
489
  flipbooks.forEach((f, i) => {
386
490
  const at = `flipbooks[${i}]`;
387
491
  if (!f || typeof f !== 'object')
@@ -416,8 +520,26 @@ export function parseVfx(value) {
416
520
  * this, so an effect that needs nothing new still plays on 1.36.
417
521
  */
418
522
  export function minimumVersion(d) {
523
+ if (d.lights !== undefined)
524
+ return 5;
525
+ if (d.emitters.some((e) => e.mesh !== undefined || e.sizeOverLifeXYZ !== undefined) || d.meshes !== undefined)
526
+ return 4;
419
527
  return d.emitters.some((e) => e.look?.type === 'material') ? 3 : 2;
420
528
  }
529
+ /** A new mesh layer: a soft additive ring on the ground, for the editor's "Add" and the agent. */
530
+ export function meshLayerDefaults() {
531
+ return {
532
+ enabled: true, shape: { type: 'ring', inner: .8, outer: 1 }, position: [0, .02, 0], rotation: [0, 0, 0], scale: [1, 1, 1],
533
+ facing: 'none', start: 0, life: null, color: '#ffffff', intensity: 1, blend: 'additive', side: 'both',
534
+ material: { ...materialDefaults(), masks: [] },
535
+ };
536
+ }
537
+ /** A new light: a warm glow just above the origin, lit for the whole cycle. */
538
+ export function lightLayerDefaults() {
539
+ return { enabled: true, position: [0, .5, 0], color: '#ffb066', intensity: 8, range: 6, start: 0, life: null, flicker: 0 };
540
+ }
541
+ export function lightLayer(id, patch = {}) { return { id, ...lightLayerDefaults(), ...patch }; }
542
+ export function meshLayer(id, patch = {}) { return { id, ...meshLayerDefaults(), ...patch }; }
421
543
  /**
422
544
  * The most particles an effect can have alive at once, estimated: per enabled
423
545
  * emitter, rate x longest life plus every burst, and for sub-emitters, the
@@ -2,6 +2,7 @@ export * from './document.js';
2
2
  export * from './templates.js';
3
3
  export { VfxInstance } from './VfxInstance.js';
4
4
  export * from './material.js';
5
+ export * from './mesh.js';
5
6
  export type { VfxInstanceOptions, VfxTextureSource } from './VfxInstance.js';
6
7
  export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
7
8
  export type { LoadVfxOptions } from './load.js';
package/dist/vfx/index.js CHANGED
@@ -7,4 +7,5 @@ export * from './document.js';
7
7
  export * from './templates.js';
8
8
  export { VfxInstance } from './VfxInstance.js';
9
9
  export * from './material.js';
10
+ export * from './mesh.js';
10
11
  export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
@@ -19,7 +19,10 @@ export declare class VfxEffect {
19
19
  readonly textures: Map<string, T.Texture>;
20
20
  private disposed;
21
21
  constructor(document: VfxDocument, textures: Map<string, T.Texture>);
22
- spawn(): VfxInstance;
22
+ /** `{ lights: false }`: this copy builds no lights (see VfxInstanceOptions). */
23
+ spawn(options?: {
24
+ lights?: boolean;
25
+ }): VfxInstance;
23
26
  /** Frees the shared textures. Dispose the spawned instances first. */
24
27
  dispose(): void;
25
28
  }
package/dist/vfx/load.js CHANGED
@@ -18,10 +18,11 @@ export class VfxEffect {
18
18
  this.textures = textures;
19
19
  this.disposed = false;
20
20
  }
21
- spawn() {
21
+ /** `{ lights: false }`: this copy builds no lights (see VfxInstanceOptions). */
22
+ spawn(options = {}) {
22
23
  if (this.disposed)
23
24
  throw new Error(`VfxEffect "${this.document.name}" was disposed`);
24
- return new VfxInstance(this.document, { textures: this.textures });
25
+ return new VfxInstance(this.document, { textures: this.textures, lights: options.lights });
25
26
  }
26
27
  /** Frees the shared textures. Dispose the spawned instances first. */
27
28
  dispose() { this.disposed = true; for (const t of this.textures.values())
@@ -47,12 +47,15 @@ export interface NoiseSource {
47
47
  export type MaskSource = NoiseSource
48
48
  /**
49
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. `center` is in UVs, v up.
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.
51
53
  */
52
54
  | {
53
55
  type: 'gradient';
54
- fill: 'linear' | 'radial' | 'square';
56
+ fill: 'linear' | 'radial' | 'square' | 'band';
55
57
  center: [number, number];
58
+ width: number;
56
59
  }
57
60
  /** The part-1 particle shapes, plus a ring (`radius` and `width` as fractions of the half-size). */
58
61
  | {
@@ -101,6 +104,7 @@ export interface Mask {
101
104
  strength: Animated;
102
105
  }
103
106
  export interface Material {
107
+ /** 0-3. None: the whole surface, solid (a mesh layer's default). */
104
108
  masks: Mask[];
105
109
  /** Taken off the mask value: 0 = whole, 1 = gone. Animate it over life to erode a particle away. */
106
110
  dissolve: Animated;
@@ -124,8 +128,26 @@ export interface Material {
124
128
  opacity: Animated;
125
129
  /** Brightness; above 1 is HDR. Multiplies the emitter's `intensity`. */
126
130
  emission: Animated;
127
- /** blend: soft alpha. cutout: hard edge at alpha 0.5. dither: a stipple instead of transparency. */
131
+ /** blend: soft alpha. cutout: opaque above `cutoff`, gone below (Godot's alpha scissor). dither: a stipple instead of transparency. */
128
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
+ };
129
151
  }
130
152
  export declare const MATERIAL_LIMITS: {
131
153
  readonly masks: 3;
@@ -135,7 +157,7 @@ export declare const ANIMATED_FIELDS: {
135
157
  readonly dissolve: readonly [-1, 2];
136
158
  readonly threshold: readonly [-1, 2];
137
159
  readonly opacity: readonly [0, 1];
138
- readonly emission: readonly [0, 16];
160
+ readonly emission: readonly [0, 32];
139
161
  };
140
162
  export declare function noiseDefaults(): NoiseSource;
141
163
  export declare function maskDefaults(source?: MaskSource): Mask;
@@ -180,6 +202,8 @@ export interface CompiledMaterial {
180
202
  /** Image filenames, by mask index, the caller binds into `uMask<i>`. */
181
203
  images: Map<number, string>;
182
204
  alphaMode: Material['alphaMode'];
205
+ /** The vertex shader pushes along the normal by `vfxDisplace(uv, life)` (defined in `code`). */
206
+ displace: boolean;
183
207
  dispose(): void;
184
208
  }
185
209
  export declare function compileMaterial(m: Material): CompiledMaterial;
@@ -24,7 +24,7 @@ import { sampleCurve, sampleGradient } from './document.js';
24
24
  /** Binbun's twelve (`util/blend.gdshaderinc`), in its order. dodge is a / (1 - b); linearBurn a + b - 1. */
25
25
  export const MASK_BLENDS = ['add', 'subtract', 'multiply', 'min', 'max', 'screen', 'overlay', 'hardLight', 'softLight', 'dodge', 'burn', 'linearBurn'];
26
26
  export const MATERIAL_LIMITS = { masks: 3, curves: 8 };
27
- export const ANIMATED_FIELDS = { dissolve: [-1, 2], threshold: [-1, 2], opacity: [0, 1], emission: [0, 16] };
27
+ export const ANIMATED_FIELDS = { dissolve: [-1, 2], threshold: [-1, 2], opacity: [0, 1], emission: [0, 32] };
28
28
  export function noiseDefaults() {
29
29
  return { type: 'noise', kind: 'perlin', fractal: 'fbm', octaves: 4, frequency: 4, seed: 1, warp: 0, pingpong: 2, size: 256 };
30
30
  }
@@ -39,7 +39,8 @@ export function materialDefaults() {
39
39
  return {
40
40
  masks: [maskDefaults(shapeSource('dot')), { ...maskDefaults(noiseDefaults()), blend: 'multiply', randomOffset: true }],
41
41
  dissolve: 0, threshold: 0, softness: .3, ramp: 'smooth', power: 1, edge: { width: 0, color: '#ffffff', emission: 2 },
42
- color: { stops: [[0, '#ffffff', 1]] }, opacity: 1, emission: 1, alphaMode: 'blend',
42
+ color: { stops: [[0, '#ffffff', 1]] }, opacity: 1, emission: 1, alphaMode: 'blend', cutoff: .5,
43
+ rim: { strength: 0, power: 2, mode: 'edge' }, displace: { amount: 0, offset: .5 },
43
44
  };
44
45
  }
45
46
  const isCurve = (a) => typeof a === 'object' && a !== null;
@@ -95,8 +96,23 @@ export function parseMaterial(input, at, fail, h) {
95
96
  h.checkGradient(m.color, `${at}.color`);
96
97
  if (!['blend', 'cutout', 'dither'].includes(m.alphaMode))
97
98
  fail(`${at}.alphaMode must be "blend", "cutout" or "dither"`);
98
- if (!Array.isArray(m.masks) || m.masks.length < 1 || m.masks.length > MATERIAL_LIMITS.masks)
99
- fail(`${at}.masks must be a list of 1-${MATERIAL_LIMITS.masks}`);
99
+ m.rim = { ...base.rim, ...m.rim };
100
+ known(m.rim, ['strength', 'power', 'mode'], `${at}.rim`, fail);
101
+ if (!num(m.rim.strength, 0, 1))
102
+ fail(`${at}.rim.strength must be 0-1`);
103
+ if (!num(m.rim.power, .25, 8))
104
+ fail(`${at}.rim.power must be 0.25-8`);
105
+ if (m.rim.mode !== 'edge' && m.rim.mode !== 'center')
106
+ fail(`${at}.rim.mode must be "edge" or "center"`);
107
+ m.displace = { ...base.displace, ...m.displace };
108
+ known(m.displace, ['amount', 'offset'], `${at}.displace`, fail);
109
+ animated(m.displace.amount, `${at}.displace.amount`, -5, 5);
110
+ if (!num(m.cutoff, 0, 1))
111
+ fail(`${at}.cutoff must be 0-1`);
112
+ if (!num(m.displace.offset, 0, 1))
113
+ fail(`${at}.displace.offset must be 0-1`);
114
+ if (!Array.isArray(m.masks) || m.masks.length > MATERIAL_LIMITS.masks)
115
+ fail(`${at}.masks must be a list of 0-${MATERIAL_LIMITS.masks} (none = solid)`);
100
116
  m.masks = m.masks.map((raw, i) => {
101
117
  const mat = `${at}.masks[${i}]`;
102
118
  if (!raw || typeof raw !== 'object' || Array.isArray(raw))
@@ -158,10 +174,12 @@ function parseSource(s, at, fail, texturePattern) {
158
174
  return n;
159
175
  }
160
176
  if (type === 'gradient') {
161
- const g = { fill: 'radial', center: [.5, .5], ...s };
162
- known(g, ['type', 'fill', 'center'], at, fail);
163
- if (!['linear', 'radial', 'square'].includes(g.fill))
164
- fail(`${at}.fill must be linear, radial or square`);
177
+ const g = { fill: 'radial', center: [.5, .5], width: .25, ...s };
178
+ known(g, ['type', 'fill', 'center', 'width'], at, fail);
179
+ if (!['linear', 'radial', 'square', 'band'].includes(g.fill))
180
+ fail(`${at}.fill must be linear, radial, square or band`);
181
+ if (!num(g.width, .001, 1))
182
+ fail(`${at}.width must be 0.001-1`);
165
183
  if (!Array.isArray(g.center) || g.center.length !== 2 || !g.center.every((x) => num(x, -1, 2)))
166
184
  fail(`${at}.center must be [u, v], each -1-2`);
167
185
  return g;
@@ -197,6 +215,8 @@ function curveFields(m) {
197
215
  if (isCurve(v))
198
216
  out.push({ key: k, value: v });
199
217
  }
218
+ if (isCurve(m.displace.amount))
219
+ out.push({ key: 'displace', value: m.displace.amount });
200
220
  m.masks.forEach((k, i) => {
201
221
  if (isCurve(k.strength))
202
222
  out.push({ key: `strength${i}`, value: k.strength });
@@ -362,6 +382,8 @@ function sourceCode(s, i, lod) {
362
382
  case 'image': return s.channel === 'r' ? `${tex('uv')}.r` : s.channel === 'a' ? `${tex('uv')}.a` : `(dot(${tex('uv')}.rgb, vec3(0.2126, 0.7152, 0.0722)) * ${tex('uv')}.a)`;
363
383
  case 'gradient': {
364
384
  const c = `vec2(${glslFloat(s.center[0])}, ${glslFloat(s.center[1])})`;
385
+ if (s.fill === 'band')
386
+ return `clamp(1.0 - abs(fract(uv.x) - ${glslFloat(s.center[0])}) / ${glslFloat(s.width)}, 0.0, 1.0)`;
365
387
  return s.fill === 'linear' ? 'fract(uv.x)' : s.fill === 'radial' ? `(1.0 - clamp(length(fract(uv) - ${c}) * 2.0, 0.0, 1.0))` : `(1.0 - clamp(max(abs(fract(uv.x) - ${c}.x), abs(fract(uv.y) - ${c}.y)) * 2.0, 0.0, 1.0))`;
366
388
  }
367
389
  case 'shape': return `vfxShape${s.shape[0].toUpperCase()}${s.shape.slice(1)}(fract(uv) * 2.0 - 1.0, uShape${i})`;
@@ -390,11 +412,15 @@ export function compileMaterial(m) {
390
412
  uDissolve: { value: isCurve(m.dissolve) ? 0 : m.dissolve }, uThreshold: { value: isCurve(m.threshold) ? 0 : m.threshold },
391
413
  uSoftness: { value: m.softness }, uPower: { value: m.power }, uOpacity: { value: isCurve(m.opacity) ? 1 : m.opacity }, uEmission: { value: isCurve(m.emission) ? 1 : m.emission },
392
414
  uEdge: { value: new T.Vector3(m.edge.width, m.edge.emission, 0) }, uEdgeColor: { value: new T.Color(m.edge.color) },
415
+ uRim: { value: new T.Vector3(m.rim.strength, m.rim.power, m.rim.mode === 'edge' ? 1 : 0) },
416
+ uDisplace: { value: new T.Vector2(isCurve(m.displace.amount) ? 1 : m.displace.amount, m.displace.offset) },
417
+ uCutoff: { value: m.cutoff },
393
418
  };
394
419
  const owned = [uniforms.uRamp.value, uniforms.uCurves.value];
395
420
  const noise = [];
396
421
  const images = new Map();
397
422
  const decl = [];
423
+ const fns = [];
398
424
  const body = [];
399
425
  m.masks.forEach((k, i) => {
400
426
  const s = k.source;
@@ -423,21 +449,26 @@ export function compileMaterial(m) {
423
449
  }
424
450
  const polar = k.polar ? `{ vec2 c = uv0 - 0.5; uv = vec2(atan(c.x, c.y) / 6.2831853 + 0.5, length(c) * 2.0); }` : '';
425
451
  const random = k.randomOffset ? ` + life.y * vec2(17.31, 7.97)` : '';
426
- body.push(` { vec2 uv = uv0; ${polar}
427
- uv = uv * uScale${i} - uScroll${i} * uTime${random};
428
- float sa = sin(uSpin${i} * uTime + uTurn${i}), ca = cos(uSpin${i} * uTime + uTurn${i}); uv = mat2(ca, sa, -sa, ca) * (uv - 0.5) + 0.5;
429
- float b = ${sourceCode(s, i, k.polar)};${k.invert ? ' b = 1.0 - b;' : ''}${k.levels ? ` b = smoothstep(uLevels${i}.x, uLevels${i}.y, b);` : ''}${isCurve(k.offset) || k.offset !== 0 ? ` b = clamp(b + ${value(`offset${i}`, `uOffset${i}`)}, 0.0, 1.0);` : ''}
430
- ${i === 0 ? 'm = b;' : `float a = m; m = mix(a, ${BLEND_CODE[k.blend]}, clamp(${value(`strength${i}`, `uStrength${i}`)}, 0.0, 1.0));`} }`);
452
+ // One function per mask, so a vertex shader can call mask 0 for displacement.
453
+ fns.push(`float vfxMask${i}(vec2 uv0, vec2 life){ vec2 uv = uv0; ${polar}
454
+ uv = uv * uScale${i} - uScroll${i} * uTime${random};
455
+ float sa = sin(uSpin${i} * uTime + uTurn${i}), ca = cos(uSpin${i} * uTime + uTurn${i}); uv = mat2(ca, sa, -sa, ca) * (uv - 0.5) + 0.5;
456
+ float b = ${sourceCode(s, i, k.polar)};${k.invert ? ' b = 1.0 - b;' : ''}${k.levels ? ` b = smoothstep(uLevels${i}.x, uLevels${i}.y, b);` : ''}${isCurve(k.offset) || k.offset !== 0 ? ` b = clamp(b + ${value(`offset${i}`, `uOffset${i}`)}, 0.0, 1.0);` : ''}
457
+ return b; }`);
458
+ body.push(i === 0 ? ' m = vfxMask0(uv0, life);' : ` { float a = m, b = vfxMask${i}(uv0, life); m = mix(a, ${BLEND_CODE[k.blend]}, clamp(${value(`strength${i}`, `uStrength${i}`)}, 0.0, 1.0)); }`);
431
459
  });
432
460
  const code = `
433
461
  uniform float uTime; uniform sampler2D uRamp; uniform sampler2D uCurves;
434
462
  uniform float uDissolve; uniform float uThreshold; uniform float uSoftness; uniform float uPower; uniform float uOpacity; uniform float uEmission;
435
- uniform vec3 uEdge; uniform vec3 uEdgeColor;
463
+ uniform vec3 uEdge; uniform vec3 uEdgeColor; uniform vec3 uRim; uniform vec2 uDisplace; uniform float uCutoff;
436
464
  ${decl.join('\n')}
437
465
  ${SHAPES}
438
466
  float vfxCurve(float row, float t){ return texture2D(uCurves, vec2((clamp(t, 0.0, 1.0) * 255.0 + 0.5) / 256.0, (row + 0.5) / ${glslFloat(rows)})).r; }
439
- vec4 vfxMaterial(vec2 uv0, vec2 life){
440
- float m = 0.0;
467
+ ${fns.join('\n')}
468
+ ${m.masks.length ? `float vfxDisplace(vec2 uv, vec2 life){ return (vfxMask0(uv, life) - uDisplace.y) * ${value('displace', 'uDisplace.x')}; }` : 'float vfxDisplace(vec2 uv, vec2 life){ return 0.0; }'}
469
+ /** facing: |dot(normal, view)|, 1 for a camera-facing quad. */
470
+ vec4 vfxMaterial(vec2 uv0, vec2 life, float facing){
471
+ float m = ${m.masks.length ? '0.0' : '1.0'};
441
472
  ${body.join('\n')}
442
473
  m = clamp(m, 0.0, 1.0);
443
474
  float v = m - ${value('dissolve', 'uDissolve')};
@@ -446,10 +477,11 @@ ${body.join('\n')}
446
477
  vec4 ramp = texture2D(uRamp, vec2(clamp(v, 0.0, 1.0) * (255.0 / 256.0) + 0.5 / 256.0, 0.5));
447
478
  vec3 rgb = ramp.rgb;
448
479
  if (uEdge.x > 0.0) { float e = 1.0 - smoothstep(th, th + uEdge.x, v); rgb = mix(rgb, uEdgeColor * uEdge.y, e * step(th, v)); }
480
+ if (uRim.x > 0.0) { float f = pow(1.0 - clamp(facing, 0.0, 1.0), uRim.y); alpha *= mix(1.0, uRim.z > 0.5 ? f : 1.0 - f, uRim.x); }
449
481
  return vec4(rgb * max(0.0, ${value('emission', 'uEmission')}), ramp.a * alpha * clamp(${value('opacity', 'uOpacity')}, 0.0, 1.0));
450
482
  }`;
451
483
  return {
452
- code, uniforms, images, alphaMode: m.alphaMode,
484
+ code, uniforms, images, alphaMode: m.alphaMode, displace: m.masks.length > 0 && (isCurve(m.displace.amount) || m.displace.amount !== 0),
453
485
  dispose() { for (const t of owned)
454
486
  t.dispose(); for (const t of noise)
455
487
  releaseNoiseTexture(t); },
@@ -470,14 +502,14 @@ export const MATERIAL_PRESETS = {
470
502
  masks: [
471
503
  mask(noise({ kind: 'perlin', fractal: 'fbm', octaves: 3, frequency: 6, warp: .25 }), { scale: [.6, .6], scroll: [0, .2], randomOffset: true }),
472
504
  mask(noise({ kind: 'perlin', fractal: 'pingpong', octaves: 1, frequency: 10, pingpong: 1, seed: 3 }), { invert: true, scale: [.4, .5], scroll: [0, -.1], randomOffset: true, blend: 'dodge', strength: .76 }),
473
- mask({ type: 'gradient', fill: 'radial', center: [.5, .5] }),
505
+ mask({ type: 'gradient', fill: 'radial', center: [.5, .5], width: .25 }),
474
506
  ],
475
507
  threshold: 0, softness: 1, ramp: 'linear', power: 3, emission: 1.5, color: { stops: [[0, '#4b4b4b', 1]] },
476
508
  }),
477
509
  fireCore: () => ({
478
510
  ...materialDefaults(),
479
511
  masks: [
480
- mask({ type: 'gradient', fill: 'radial', center: [.5, .5] }, { levels: [-.2, 1] }),
512
+ mask({ type: 'gradient', fill: 'radial', center: [.5, .5], width: .25 }, { levels: [-.2, 1] }),
481
513
  mask(noise({ kind: 'perlin', fractal: 'ridged', octaves: 3, frequency: 6, warp: .35 }), { scale: [.15, .6], scroll: [0, .4], randomOffset: true }),
482
514
  ],
483
515
  threshold: .3, softness: .2, emission: curve([0, 4], [.3, 1.4], [1, 1]),
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Mesh layers and mesh-shaped particles (format v3, umicat-design ADR-055
3
+ * step 2). The shapes are Godot's primitive meshes with Godot's parameters,
4
+ * so a rebuild copies the numbers: QuadMesh faces +Z, PlaneMesh faces +Y,
5
+ * Cylinder / Sphere / Torus stand on the Y axis.
6
+ */
7
+ import * as T from 'three';
8
+ import type { Curve, Gradient, Vec3 } from './document.js';
9
+ import type { CompiledMaterial, Material } from './material.js';
10
+ export type MeshShape =
11
+ /** Upright card in the XY plane, facing +Z. */
12
+ {
13
+ type: 'quad';
14
+ size: [number, number];
15
+ }
16
+ /** Flat on the ground (XZ), facing up. */
17
+ | {
18
+ type: 'plane';
19
+ size: [number, number];
20
+ }
21
+ /** `height` other than 2 x radius squashes it (Godot SphereMesh). */
22
+ | {
23
+ type: 'sphere';
24
+ radius: number;
25
+ height: number;
26
+ hemisphere: boolean;
27
+ }
28
+ /** top 0 is a cone. `caps` false leaves it an open tube (most effect rings and columns). */
29
+ | {
30
+ type: 'cylinder';
31
+ top: number;
32
+ bottom: number;
33
+ height: number;
34
+ caps: boolean;
35
+ }
36
+ /** Lies flat, around Y (Godot TorusMesh). */
37
+ | {
38
+ type: 'torus';
39
+ inner: number;
40
+ outer: number;
41
+ } | {
42
+ type: 'box';
43
+ size: Vec3;
44
+ }
45
+ /** A flat annulus on the ground: a shockwave, a target circle. */
46
+ | {
47
+ type: 'ring';
48
+ inner: number;
49
+ outer: number;
50
+ };
51
+ export interface MeshLayer {
52
+ id: string;
53
+ enabled: boolean;
54
+ shape: MeshShape;
55
+ position: Vec3;
56
+ rotation: Vec3;
57
+ scale: Vec3;
58
+ /** none: as placed. camera: a quad or plane turned to face the viewer, keeping its position and size (other shapes ignore it). */
59
+ facing: 'none' | 'camera';
60
+ /** Seconds into each cycle it appears, and for how long (null: to the end of the cycle). */
61
+ start: number;
62
+ life: number | null;
63
+ /** Over the layer's own life (0 = start, 1 = end). Multiplies `scale`. */
64
+ scaleOverLife?: Curve;
65
+ color: string;
66
+ colorOverLife?: Gradient;
67
+ alphaOverLife?: Curve;
68
+ intensity: number;
69
+ blend: 'normal' | 'additive';
70
+ side: 'front' | 'back' | 'both';
71
+ material: Material;
72
+ }
73
+ export declare const MESH_SHAPES: Record<MeshShape['type'], () => MeshShape>;
74
+ type Fail = (why: string) => never;
75
+ /** Fills a shape's missing parameters from its defaults and checks them. */
76
+ export declare function parseMeshShape(raw: unknown, at: string, fail: Fail): MeshShape;
77
+ /**
78
+ * The geometry, built once per layer. Enough segments for vertex
79
+ * displacement to read as a surface (Binbun subdivides its cards 16x16 for the
80
+ * same reason).
81
+ */
82
+ export declare function meshGeometry(s: MeshShape): T.BufferGeometry;
83
+ /** Ring UVs from three.js are planar; an effect ring wants u around and v across, like a cylinder's. */
84
+ export declare function fixRingUv(g: T.BufferGeometry, s: MeshShape): T.BufferGeometry<T.NormalBufferAttributes, T.BufferGeometryEventMap>;
85
+ /** A mesh layer: one mesh, its colour and life from uniforms. */
86
+ export declare const meshLayerVertex: (c: CompiledMaterial) => string;
87
+ /**
88
+ * A mesh particle: the mesh, scaled by the particle's size, stood on a basis
89
+ * whose Y is the particle's velocity (align velocity), the emitter's axis
90
+ * (axis) or the emitter's own up (otherwise), and turned by its angle about
91
+ * that Y -- Godot's transform_align / rotate_y.
92
+ */
93
+ export declare const meshParticleVertex: (c: CompiledMaterial) => string;
94
+ /** Shared by mesh layers and mesh particles: the material, times the colour, with the alpha mode. */
95
+ export declare const meshFragment: (c: CompiledMaterial) => string;
96
+ export {};
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Mesh layers and mesh-shaped particles (format v3, umicat-design ADR-055
3
+ * step 2). The shapes are Godot's primitive meshes with Godot's parameters,
4
+ * so a rebuild copies the numbers: QuadMesh faces +Z, PlaneMesh faces +Y,
5
+ * Cylinder / Sphere / Torus stand on the Y axis.
6
+ */
7
+ import * as T from 'three';
8
+ export const MESH_SHAPES = {
9
+ quad: () => ({ type: 'quad', size: [1, 1] }),
10
+ plane: () => ({ type: 'plane', size: [2, 2] }),
11
+ sphere: () => ({ type: 'sphere', radius: .5, height: 1, hemisphere: false }),
12
+ cylinder: () => ({ type: 'cylinder', top: .5, bottom: .5, height: 1, caps: false }),
13
+ torus: () => ({ type: 'torus', inner: .4, outer: .5 }),
14
+ box: () => ({ type: 'box', size: [1, 1, 1] }),
15
+ ring: () => ({ type: 'ring', inner: .8, outer: 1 }),
16
+ };
17
+ const num = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
18
+ /** Fills a shape's missing parameters from its defaults and checks them. */
19
+ export function parseMeshShape(raw, at, fail) {
20
+ const type = raw?.type;
21
+ if (!raw || typeof raw !== 'object' || !(type in MESH_SHAPES))
22
+ return fail(`${at}.type must be one of ${Object.keys(MESH_SHAPES).join(', ')}`);
23
+ const base = MESH_SHAPES[type]();
24
+ for (const k of Object.keys(raw))
25
+ if (!(k in base))
26
+ fail(`${at}.${k} is not a ${type} field (expected ${Object.keys(base).join(', ')})`);
27
+ const s = { ...base, ...raw };
28
+ const pos = (k, v, max = 100) => { if (!num(v, 0, max))
29
+ fail(`${at}.${k} must be 0-${max}`); };
30
+ const vec = (k, v, n) => { if (!Array.isArray(v) || v.length !== n || !v.every((x) => num(x, 0, 100)))
31
+ fail(`${at}.${k} must be [${n === 2 ? 'w, h' : 'x, y, z'}], each 0-100`); };
32
+ switch (s.type) {
33
+ case 'quad':
34
+ case 'plane':
35
+ vec('size', s.size, 2);
36
+ break;
37
+ case 'box':
38
+ vec('size', s.size, 3);
39
+ break;
40
+ case 'sphere':
41
+ pos('radius', s.radius);
42
+ pos('height', s.height, 200);
43
+ if (typeof s.hemisphere !== 'boolean')
44
+ fail(`${at}.hemisphere must be a boolean`);
45
+ break;
46
+ case 'cylinder':
47
+ pos('top', s.top);
48
+ pos('bottom', s.bottom);
49
+ pos('height', s.height);
50
+ if (typeof s.caps !== 'boolean')
51
+ fail(`${at}.caps must be a boolean`);
52
+ if (s.top === 0 && s.bottom === 0)
53
+ fail(`${at} needs top or bottom above 0`);
54
+ break;
55
+ case 'torus':
56
+ case 'ring':
57
+ pos('outer', s.outer);
58
+ if (!num(s.inner, 0, s.outer))
59
+ fail(`${at}.inner must be 0-outer (${s.outer})`);
60
+ break;
61
+ }
62
+ return s;
63
+ }
64
+ /**
65
+ * The geometry, built once per layer. Enough segments for vertex
66
+ * displacement to read as a surface (Binbun subdivides its cards 16x16 for the
67
+ * same reason).
68
+ */
69
+ export function meshGeometry(s) {
70
+ switch (s.type) {
71
+ case 'quad': return new T.PlaneGeometry(s.size[0], s.size[1], 16, 16);
72
+ case 'plane': return new T.PlaneGeometry(s.size[0], s.size[1], 16, 16).rotateX(-Math.PI / 2);
73
+ case 'sphere': {
74
+ const g = new T.SphereGeometry(Math.max(s.radius, 1e-4), 32, s.hemisphere ? 8 : 16, 0, Math.PI * 2, 0, s.hemisphere ? Math.PI / 2 : Math.PI);
75
+ return s.radius > 0 && Math.abs(s.height - 2 * s.radius) > 1e-6 ? g.scale(1, s.height / (2 * s.radius), 1) : g;
76
+ }
77
+ case 'cylinder': return new T.CylinderGeometry(s.top, s.bottom, s.height, 32, 8, !s.caps);
78
+ case 'torus': return new T.TorusGeometry((s.inner + s.outer) / 2, Math.max(1e-4, (s.outer - s.inner) / 2), 16, 48).rotateX(-Math.PI / 2);
79
+ case 'box': return new T.BoxGeometry(s.size[0], s.size[1], s.size[2]);
80
+ case 'ring': return new T.RingGeometry(s.inner, s.outer, 64, 1).rotateX(-Math.PI / 2);
81
+ }
82
+ }
83
+ /** Ring UVs from three.js are planar; an effect ring wants u around and v across, like a cylinder's. */
84
+ export function fixRingUv(g, s) {
85
+ if (s.type !== 'ring')
86
+ return g;
87
+ const p = g.getAttribute('position'), uv = g.getAttribute('uv');
88
+ for (let i = 0; i < p.count; i++) {
89
+ const x = p.getX(i), z = p.getZ(i), r = Math.hypot(x, z);
90
+ uv.setXY(i, Math.atan2(z, x) / (Math.PI * 2) + .5, s.outer > s.inner ? (r - s.inner) / (s.outer - s.inner) : 0);
91
+ }
92
+ uv.needsUpdate = true;
93
+ return g;
94
+ }
95
+ const DISPLACE = (c, life) => c.displace ? `p += n * vfxDisplace(uv, ${life});` : '';
96
+ /** A mesh layer: one mesh, its colour and life from uniforms. */
97
+ export const meshLayerVertex = (c) => `
98
+ uniform vec4 uLayerColor; uniform vec2 uLayerLife; uniform float uFacing;
99
+ varying vec2 vUv; varying vec4 vColor; varying vec2 vLife; varying vec3 vN; varying vec3 vV;
100
+ ${c.code}
101
+ void main(){
102
+ vec3 p = position, n = normal;
103
+ vUv = uv; vColor = uLayerColor; vLife = uLayerLife;
104
+ ${DISPLACE(c, 'uLayerLife')}
105
+ if (uFacing > 0.5) {
106
+ // Turned to face the viewer, keeping its position and its own size.
107
+ vec4 c0 = modelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0);
108
+ // uFacing 1: a quad (its XY), 2: a plane (its XZ, z toward the viewer = down on screen).
109
+ c0.xy += uFacing < 1.5 ? vec2(p.x * length(modelMatrix[0].xyz), p.y * length(modelMatrix[1].xyz))
110
+ : vec2(p.x * length(modelMatrix[0].xyz), -p.z * length(modelMatrix[2].xyz));
111
+ vV = -c0.xyz; vN = vec3(0.0, 0.0, 1.0);
112
+ gl_Position = projectionMatrix * c0;
113
+ return;
114
+ }
115
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
116
+ vV = -mv.xyz; vN = normalize(normalMatrix * n);
117
+ gl_Position = projectionMatrix * mv;
118
+ }`;
119
+ /**
120
+ * A mesh particle: the mesh, scaled by the particle's size, stood on a basis
121
+ * whose Y is the particle's velocity (align velocity), the emitter's axis
122
+ * (axis) or the emitter's own up (otherwise), and turned by its angle about
123
+ * that Y -- Godot's transform_align / rotate_y.
124
+ */
125
+ export const meshParticleVertex = (c) => `
126
+ attribute vec3 iPos; attribute vec4 iColor; attribute vec4 iMisc; attribute vec3 iVel; attribute vec2 iLife; attribute vec3 iAxes;
127
+ uniform float uAlign; uniform mat3 uOrient; uniform vec3 uAxis;
128
+ varying vec2 vUv; varying vec4 vColor; varying vec2 vLife; varying vec3 vN; varying vec3 vV;
129
+ ${c.code}
130
+ void main(){
131
+ vec3 p = position, n = normal;
132
+ vUv = uv; vColor = iColor; vLife = iLife;
133
+ ${DISPLACE(c, 'iLife')}
134
+ vec3 up = uOrient * vec3(0.0, 1.0, 0.0);
135
+ if (uAlign > 0.5 && uAlign < 1.5 && dot(iVel, iVel) > 1e-10) up = normalize(iVel);
136
+ else if (uAlign > 2.5) up = normalize(uAxis);
137
+ vec3 ref = abs(up.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
138
+ vec3 side = normalize(cross(ref, up)), fwd = cross(side, up);
139
+ if (uAlign < 0.5 || (uAlign > 1.5 && uAlign < 2.5)) { side = uOrient * vec3(1.0, 0.0, 0.0); fwd = uOrient * vec3(0.0, 0.0, 1.0); }
140
+ float s = sin(iMisc.y), co = cos(iMisc.y);
141
+ vec3 sx = side * co - fwd * s, sz = side * s + fwd * co;
142
+ mat3 basis = mat3(sx, up, sz);
143
+ vec4 mv = modelViewMatrix * vec4(iPos + basis * (p * iMisc.x * iAxes), 1.0);
144
+ vV = -mv.xyz; vN = normalize((modelViewMatrix * vec4(basis * (n / max(iAxes, vec3(1e-4))), 0.0)).xyz);
145
+ gl_Position = projectionMatrix * mv;
146
+ }`;
147
+ /** Shared by mesh layers and mesh particles: the material, times the colour, with the alpha mode. */
148
+ export const meshFragment = (c) => `
149
+ varying vec2 vUv; varying vec4 vColor; varying vec2 vLife; varying vec3 vN; varying vec3 vV;
150
+ ${c.code}
151
+ float vfxBayer(vec2 p){ ivec2 q = ivec2(mod(p, 4.0)); int i = q.x + q.y * 4;
152
+ float m[16] = float[16](0.,8.,2.,10.,12.,4.,14.,6.,3.,11.,1.,9.,15.,7.,13.,5.); return (m[i] + 0.5) / 16.0; }
153
+ void main(){
154
+ float facing = abs(dot(normalize(vN), normalize(vV)));
155
+ vec4 m = vfxMaterial(vUv, vLife, facing);
156
+ float a = m.a * vColor.a;
157
+ ${c.alphaMode === 'cutout' ? 'if (a < uCutoff) discard; a = 1.0;' : c.alphaMode === 'dither' ? 'if (a < vfxBayer(gl_FragCoord.xy)) discard; a = 1.0;' : 'if (a <= 0.002) discard;'}
158
+ gl_FragColor = vec4(m.rgb * vColor.rgb, a);
159
+ #include <tonemapping_fragment>
160
+ #include <colorspace_fragment>
161
+ }`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.37.0",
3
+ "version": "1.39.0",
4
4
  "description": "Three.js runtime for Umicat games: the scene3d design format, its loader with physics, a kinematic character controller, and the Umicat platform via @umicat/platform-sdk.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",