reze-engine 0.69.1 → 0.69.3

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.
@@ -61,6 +61,21 @@ const LINE = DIRECTIVE_LINE;
61
61
  * thing to write, so it has to be the accepted thing to write.
62
62
  */
63
63
  export const DIRECTIVE_NOTE = /(?:^|\s)(?:—|--|\/\/|#)\s/;
64
+ /** The note after the arguments, or "" — see DIRECTIVE_NOTE. */
65
+ function noteOf(rest) {
66
+ const m = DIRECTIVE_NOTE.exec(rest);
67
+ return m ? rest.slice(m.index + m[0].length).trim() : "";
68
+ }
69
+ /** A dial's labels from its note, when the note is written `English | 中文`. */
70
+ function labelsOf(rest) {
71
+ const note = noteOf(rest);
72
+ const bar = note.indexOf("|");
73
+ if (bar < 0)
74
+ return {};
75
+ const label = note.slice(0, bar).trim();
76
+ const labelZh = note.slice(bar + 1).trim();
77
+ return { ...(label ? { label } : {}), ...(labelZh ? { labelZh } : {}) };
78
+ }
64
79
  function argsOf(rest) {
65
80
  // `^` as well as `\s`: the tag's own trailing space is eaten by LINE, so a
66
81
  // note can begin at the very first character — which is what
@@ -166,12 +181,86 @@ export function parseDirectives(wgsl) {
166
181
  errors.push(`${at}: #param needs a WGSL identifier for a name`);
167
182
  return;
168
183
  }
184
+ const labels = labelsOf(m[2]);
185
+ if (kind === "bool") {
186
+ const v = rest[0]?.toLowerCase();
187
+ const on = v === "true" || v === "1" || v === "on";
188
+ const off = v === "false" || v === "0" || v === "off";
189
+ if (rest.length !== 1 || (!on && !off)) {
190
+ errors.push(`${at}: #param bool ${name} needs a default, true or false`);
191
+ return;
192
+ }
193
+ d.params.push({ name, kind: "bool", value: on ? 1 : 0, ...labels });
194
+ return;
195
+ }
196
+ if (kind === "int") {
197
+ // A count: strands, rows, petals. One f32 in the shader like a
198
+ // slider, but whole — the host steps it and a key never lands between.
199
+ const v = num(rest[0]);
200
+ if (v === null || !Number.isInteger(v)) {
201
+ errors.push(`${at}: #param int ${name} needs a whole-number default`);
202
+ return;
203
+ }
204
+ const lo = num(rest[1]);
205
+ const hi = num(rest[2]);
206
+ if ((rest[1] !== undefined) !== (rest[2] !== undefined) || (rest[1] !== undefined && (lo === null || hi === null))) {
207
+ errors.push(`${at}: #param int ${name} takes both a min and a max, or neither`);
208
+ return;
209
+ }
210
+ d.params.push({ name, kind: "int", value: v, ...(lo !== null && hi !== null ? { min: lo, max: hi } : {}), ...labels });
211
+ return;
212
+ }
213
+ if (kind === "point") {
214
+ // A place in the world, in world units — set by dragging it in the
215
+ // scene, and able to follow a character. One vec3f in the shader.
216
+ const v = rest.slice(0, 3).map(num);
217
+ if (rest.length !== 3 || v.some((x) => x === null)) {
218
+ errors.push(`${at}: #param point ${name} needs three numbers, a position like "0 10 0"`);
219
+ return;
220
+ }
221
+ d.params.push({ name, kind: "point", value: v, ...labels });
222
+ return;
223
+ }
224
+ if (kind === "bone") {
225
+ // A bone of a character, picked by the host: read as rzBone_NAME(),
226
+ // a position, a forward and whether that rig has it. The default is
227
+ // the bone's name; whose bone it is, the host decides.
228
+ if (rest.length !== 1) {
229
+ errors.push(`${at}: #param bone ${name} needs one bone name, like 右手首`);
230
+ return;
231
+ }
232
+ d.params.push({ name, kind: "bone", value: rest[0], ...labels });
233
+ return;
234
+ }
235
+ if (kind === "enum") {
236
+ // Each choice is `id` or `id|中文`; a leading `*` marks the default,
237
+ // else the first is.
238
+ const options = [];
239
+ let value = 0;
240
+ for (const raw of rest) {
241
+ const star = raw.startsWith("*");
242
+ const [id, zh] = (star ? raw.slice(1) : raw).split("|");
243
+ if (!id) {
244
+ errors.push(`${at}: #param enum ${name} has an empty choice`);
245
+ return;
246
+ }
247
+ if (star)
248
+ value = options.length;
249
+ options.push({ id, ...(zh ? { labelZh: zh } : {}) });
250
+ }
251
+ if (options.length < 2) {
252
+ errors.push(`${at}: #param enum ${name} needs at least two choices, like "rain|数字雨 dots|点阵"`);
253
+ return;
254
+ }
255
+ d.params.push({ name, kind: "enum", value, options, ...labels });
256
+ return;
257
+ }
169
258
  if (kind === "color") {
170
259
  if (!/^#[0-9a-fA-F]{6}$/.test(rest[0] ?? "")) {
171
260
  errors.push(`${at}: #param color ${name} needs a default like #3b82f6`);
172
261
  return;
173
262
  }
174
- d.params.push({ name, kind: "color", value: rest[0] });
263
+ d.params.push({ name, kind: "color", value: rest[0], ...labels });
175
264
  return;
176
265
  }
177
266
  if (kind === "vec3") {
@@ -180,7 +269,7 @@ export function parseDirectives(wgsl) {
180
269
  errors.push(`${at}: #param vec3 ${name} needs three numbers`);
181
270
  return;
182
271
  }
183
- d.params.push({ name, kind: "vec3", value: v });
272
+ d.params.push({ name, kind: "vec3", value: v, ...labels });
184
273
  return;
185
274
  }
186
275
  if (kind === "float") {
@@ -197,10 +286,10 @@ export function parseDirectives(wgsl) {
197
286
  errors.push(`${at}: #param float ${name} takes both a min and a max, or neither`);
198
287
  return;
199
288
  }
200
- d.params.push({ name, kind: "float", value: v, ...(lo !== null && hi !== null ? { min: lo, max: hi } : {}) });
289
+ d.params.push({ name, kind: "float", value: v, ...(lo !== null && hi !== null ? { min: lo, max: hi } : {}), ...labels });
201
290
  return;
202
291
  }
203
- errors.push(`${at}: #param kind must be float, color or vec3`);
292
+ errors.push(`${at}: #param kind must be float, int, color, vec3, point, bone, bool or enum`);
204
293
  return;
205
294
  }
206
295
  case "halfres":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reze-engine",
3
- "version": "0.69.1",
3
+ "version": "0.69.3",
4
4
  "description": "A lightweight WebGPU engine for real-time 3D MMD/PMX model rendering",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
package/src/engine.ts CHANGED
@@ -611,7 +611,31 @@ type SunOptions = {
611
611
  /** An effect param: number → f32, vector-like → vec3f (see setEffect).
612
612
  * Structural {x,y,z} rather than the Vec3 class so JSON-derived values (a
613
613
  * shared scene document's params) pass straight in. */
614
- export type EffectParamValue = number | { x: number; y: number; z: number }
614
+ export type EffectParamValue = number | { x: number; y: number; z: number } | EffectPointValue | EffectBoneValue
615
+
616
+ /** A `point` dial: a world position, or — with `model` — an offset from where
617
+ * that character stands, so the point travels with her. */
618
+ export type EffectPointValue = { x: number; y: number; z: number; model?: string | null }
619
+
620
+ /** A `bone` dial: a bone by name, on `model`, or on the effect's first
621
+ * character when it names none. */
622
+ export type EffectBoneValue = { bone: string; model?: string | null }
623
+
624
+ /** One key of a dial's track. `time` is seconds on the transport — the clock an
625
+ * effect's strips run on. `ease` shapes the way to the NEXT key; switches,
626
+ * lists and bones always hold, whatever it says. */
627
+ export type EffectParamKey = {
628
+ time: number
629
+ value: EffectParamValue
630
+ ease?: "linear" | "ease" | "hold"
631
+ /** The way INTO this key from the previous one, as a bezier — x1, y1, x2, y2
632
+ * in 0..1, the curve a VMD key carries. `ease` is that segment too.
633
+ * Ignored by a hold, and by dials that always hold. */
634
+ curve?: [number, number, number, number]
635
+ }
636
+
637
+ const isBoneValue = (v: EffectParamValue | undefined): v is EffectBoneValue =>
638
+ typeof v === "object" && v !== null && "bone" in v
615
639
 
616
640
  /** A vector by shape rather than by class — Vec3 satisfies it, and so does a
617
641
  * JSON object out of a scene document or a literal typed into a console. */
@@ -1049,6 +1073,17 @@ interface ModelInstance {
1049
1073
  * writes ONE float into each of them and needs no other reason to hold a
1050
1074
  * block: the whole 16-float copy exists only for materials that morph. */
1051
1075
  materialUniformBuffers: GPUBuffer[]
1076
+ /** The material each of `materialUniformBuffers` belongs to, by index. Names,
1077
+ * not PMX indices: a material with no faces draws nothing and has no buffer,
1078
+ * so the two lists do not line up with the PMX's own. */
1079
+ materialNames: string[]
1080
+ /** How much of each named material is still there, as setMaterialDissolve
1081
+ * last asked. Absent = whole. A material wears the lower of this and the
1082
+ * model's own `dissolve`. */
1083
+ materialDissolve: Map<string, number>
1084
+ /** What each material buffer was last written, so a frame that changes
1085
+ * nothing writes nothing. */
1086
+ dissolveWritten: number[]
1052
1087
  /** The outline hulls' own uniforms, for the materials that have them.
1053
1088
  *
1054
1089
  * A SEPARATE LIST because they are a separate buffer: the hull pass binds 32
@@ -1622,7 +1657,8 @@ const TEXTURE_EXTENSION_GUESSES = [".png", ".jpg", ".jpeg", ".bmp", ".tga", ".dd
1622
1657
  * darken every authored colour by the transfer curve twice.
1623
1658
  */
1624
1659
  function paramValue(p: EffectParamDecl, given: EffectParamValue | undefined): EffectParamValue {
1625
- if (given !== undefined) return given
1660
+ if (p.kind === "bone") return isBoneValue(given) ? given : { bone: typeof p.value === "string" ? p.value : "", model: null }
1661
+ if (given !== undefined) return p.kind === "int" && typeof given === "number" ? Math.round(given) : given
1626
1662
  if (p.kind === "color" && typeof p.value === "string") {
1627
1663
  const n = parseInt(p.value.slice(1), 16)
1628
1664
  return { x: ((n >> 16) & 255) / 255, y: ((n >> 8) & 255) / 255, z: (n & 255) / 255 }
@@ -1853,6 +1889,12 @@ interface EffectInstance {
1853
1889
  paramLayout: Map<string, { offset: number; comps: 1 | 3 }>
1854
1890
  paramsBuffer: GPUBuffer | null
1855
1891
  paramsData: Float32Array<ArrayBuffer>
1892
+ /** The dials the engine resolves every frame rather than once: each bone
1893
+ * dial's bone and character, and each point dial set to follow one. */
1894
+ paramBindings: Map<string, EffectBoneValue | EffectPointValue>
1895
+ /** Dials driven by keys, by name — see setEffectParamTrack. Bone keys index
1896
+ * `bones`, since the sampler carries numbers. */
1897
+ paramTracks: Map<string, { keys: ParamKey[]; bones: EffectBoneValue[]; last: ParamValue | null }>
1856
1898
  /** This effect IS a mirror — see the `#mirror` directive. Draws no shader;
1857
1899
  * the engine reads its dials and folds the scene through the plane. */
1858
1900
  hasMirror: boolean
@@ -1919,6 +1961,9 @@ interface EffectInstance {
1919
1961
  * permanently half-strength effect and a scheduled one are the same dial.
1920
1962
  */
1921
1963
  influence: number
1964
+ /** `influence` over time, keyed on the transport — a fade is two keys.
1965
+ * Null holds `influence`. */
1966
+ influenceTrack: ParamKey[] | null
1922
1967
  /** Its strips, in scene seconds — a LANE, so one effect can fire more than
1923
1968
  * once. Null or empty = on for the whole scene, which is what applying an
1924
1969
  * effect does until someone places it. */
@@ -5662,7 +5707,19 @@ export class Engine {
5662
5707
  // KIND comes from the declaration, never from the runtime type of the
5663
5708
  // value: a caller handing a number to a colour must not silently turn a
5664
5709
  // vec3f field into an f32 and shift every field after it.
5665
- const isVec = p.kind !== "float"
5710
+ if (p.kind === "bone") {
5711
+ // Three fields the engine fills each frame — where the bone is, the way
5712
+ // it points, and whether this rig has it — read through rzBone_NAME().
5713
+ for (const [field, vec] of [[p.name, true], [`${p.name}__fwd`, true], [`${p.name}__ok`, false]] as const) {
5714
+ const align = vec ? 16 : 4
5715
+ const offset = Math.ceil(cursor / align) * align
5716
+ layout.set(field, { offset: offset / 4, comps: vec ? 3 : 1 })
5717
+ fields.push(` ${field}: ${vec ? "vec3f" : "f32"},`)
5718
+ cursor = offset + (vec ? 12 : 4)
5719
+ }
5720
+ continue
5721
+ }
5722
+ const isVec = p.kind === "color" || p.kind === "vec3" || p.kind === "point"
5666
5723
  const align = isVec ? 16 : 4
5667
5724
  const offset = Math.ceil(cursor / align) * align
5668
5725
  layout.set(p.name, { offset: offset / 4, comps: isVec ? 3 : 1 })
@@ -5670,15 +5727,35 @@ export class Engine {
5670
5727
  cursor = offset + (isVec ? 12 : 4)
5671
5728
  }
5672
5729
  const paramsData = new Float32Array(Math.max(4, Math.ceil(cursor / 16) * 4))
5730
+ const paramBindings = new Map<string, EffectBoneValue | EffectPointValue>()
5673
5731
  for (const [name, value] of entries) {
5674
5732
  const slot = layout.get(name)!
5733
+ // A bone, and a point that follows someone, are resolved every frame;
5734
+ // their fields start empty and the first evaluation fills them.
5735
+ if (isBoneValue(value)) {
5736
+ paramBindings.set(name, value)
5737
+ continue
5738
+ }
5675
5739
  if (typeof value === "number") paramsData[slot.offset] = value
5676
5740
  else {
5741
+ if ("model" in value && value.model) paramBindings.set(name, value)
5677
5742
  paramsData[slot.offset] = value.x
5678
5743
  paramsData[slot.offset + 1] = value.y
5679
5744
  paramsData[slot.offset + 2] = value.z
5680
5745
  }
5681
5746
  }
5747
+ // rzBone_NAME() for each bone dial: its own struct rather than RzAnchor, so
5748
+ // the accessor stands in every module a params block is spliced into.
5749
+ const bones = d.params.filter((p) => p.kind === "bone")
5750
+ const boneWgsl = bones.length
5751
+ ? "struct RzBoneParam { pos: vec3f, fwd: vec3f, valid: bool, }\n" +
5752
+ bones
5753
+ .map(
5754
+ (p) =>
5755
+ `fn rzBone_${p.name}() -> RzBoneParam { return RzBoneParam(params.${p.name}, params.${p.name}__fwd, params.${p.name}__ok > 0.5); }\n`,
5756
+ )
5757
+ .join("")
5758
+ : ""
5682
5759
  /**
5683
5760
  * The params block, at whatever binding the pass asking has free.
5684
5761
  *
@@ -5689,7 +5766,7 @@ export class Engine {
5689
5766
  */
5690
5767
  const paramsWgsl = (binding: number) =>
5691
5768
  entries.length
5692
- ? `struct EffectParams {\n${fields.join("\n")}\n}\n@group(0) @binding(${binding}) var<uniform> params: EffectParams;\n`
5769
+ ? `struct EffectParams {\n${fields.join("\n")}\n}\n@group(0) @binding(${binding}) var<uniform> params: EffectParams;\n${boneWgsl}`
5693
5770
  : ""
5694
5771
  const paramsDecl = paramsWgsl(EFFECT_PARAMS_BINDING)
5695
5772
 
@@ -5895,6 +5972,8 @@ export class Engine {
5895
5972
  paramLayout: layout,
5896
5973
  paramsBuffer,
5897
5974
  paramsData,
5975
+ paramBindings,
5976
+ paramTracks: new Map(),
5898
5977
  hasMirror: d.mirror,
5899
5978
  stepped: d.stepped,
5900
5979
  hasBackground,
@@ -5926,6 +6005,7 @@ export class Engine {
5926
6005
  // scheduling it is something a caller does afterwards, and an install
5927
6006
  // that silently began at zero would look like a compile that failed.
5928
6007
  influence: 1,
6008
+ influenceTrack: null,
5929
6009
  window: null,
5930
6010
  weight: 1,
5931
6011
  sim: { start: null, time: null },
@@ -7514,15 +7594,158 @@ export class Engine {
7514
7594
  setEffectParam(index: number, name: string, value: EffectParamValue): void {
7515
7595
  const fx = this.effects[index]
7516
7596
  if (!fx || !fx.paramsBuffer) return
7597
+ // A keyed dial is its track's: the frame writes it only when the sampled
7598
+ // value changes, so a plain value written over it would stick until then.
7599
+ if (fx.paramTracks.has(name)) return
7600
+ if (this.writeEffectParam(fx, name, value)) this.device.queue.writeBuffer(fx.paramsBuffer, 0, fx.paramsData)
7601
+ // A bone, or a point that now follows someone, lands on the next frame's
7602
+ // evaluation; resolving it now as well means a paused scene shows it too.
7603
+ if (fx.paramBindings.has(name)) this.evaluateEffectParams()
7604
+ }
7605
+
7606
+ /** One dial into the instance's block, by its declared kind. Returns whether
7607
+ * the block changed — a bone changes only its binding, which the frame's
7608
+ * evaluation writes. */
7609
+ private writeEffectParam(fx: EffectInstance, name: string, value: EffectParamValue): boolean {
7610
+ const decl = fx.paramDecls.find((p) => p.name === name)
7517
7611
  const slot = fx.paramLayout.get(name)
7518
- if (!slot) return
7519
- if (typeof value === "number") fx.paramsData[slot.offset] = value
7520
- else {
7521
- fx.paramsData[slot.offset] = value.x
7522
- fx.paramsData[slot.offset + 1] = value.y
7523
- fx.paramsData[slot.offset + 2] = value.z
7612
+ if (!decl || !slot) return false
7613
+ if (decl.kind === "bone") {
7614
+ if (isBoneValue(value)) fx.paramBindings.set(name, value)
7615
+ return false
7616
+ }
7617
+ if (isBoneValue(value)) return false
7618
+ if (typeof value === "number") {
7619
+ fx.paramsData[slot.offset] = decl.kind === "int" ? Math.round(value) : value
7620
+ return true
7621
+ }
7622
+ if (decl.kind === "point" && "model" in value && value.model) fx.paramBindings.set(name, value)
7623
+ else fx.paramBindings.delete(name)
7624
+ fx.paramsData[slot.offset] = value.x
7625
+ fx.paramsData[slot.offset + 1] = value.y
7626
+ fx.paramsData[slot.offset + 2] = value.z
7627
+ return true
7628
+ }
7629
+
7630
+ /**
7631
+ * Drive one dial from keys on the transport — the clock the effect's strips
7632
+ * run on, so a key at a clip's start lands at the clip's start in the editor,
7633
+ * a scrub and an export alike. Null, or no keys, gives the dial back to
7634
+ * setEffectParam.
7635
+ *
7636
+ * Numbers, whole numbers, colours, vectors and points travel between keys,
7637
+ * straight or eased; switches, lists and bones hold until the next key. A
7638
+ * track lives on the instance, so an install builds fresh ones and the host
7639
+ * pushes its tracks again, as it does a schedule.
7640
+ */
7641
+ setEffectParamTrack(index: number, name: string, keys: readonly EffectParamKey[] | null): boolean {
7642
+ const fx = this.effects[index]
7643
+ const decl = fx?.paramDecls.find((p) => p.name === name)
7644
+ if (!fx || !decl) return false
7645
+ if (!keys || keys.length === 0) {
7646
+ fx.paramTracks.delete(name)
7647
+ return true
7648
+ }
7649
+ const holds = decl.kind === "bool" || decl.kind === "enum" || decl.kind === "bone"
7650
+ const bones: EffectBoneValue[] = []
7651
+ const sorted = [...keys].sort((a, b) => a.time - b.time)
7652
+ const track: ParamKey[] = []
7653
+ for (const k of sorted) {
7654
+ let v: ParamValue
7655
+ if (decl.kind === "bone") {
7656
+ if (!isBoneValue(k.value)) continue
7657
+ v = bones.push(k.value) - 1
7658
+ } else if (typeof k.value === "number") v = k.value
7659
+ else if (isBoneValue(k.value)) continue
7660
+ else v = [k.value.x, k.value.y, k.value.z]
7661
+ track.push({
7662
+ t: k.time,
7663
+ v,
7664
+ e: holds ? "hold" : (k.ease ?? "linear"),
7665
+ ...(!holds && k.curve && k.ease !== "hold" ? { b: k.curve } : {}),
7666
+ })
7667
+ }
7668
+ fx.paramTracks.set(name, { keys: track, bones, last: null })
7669
+ this.evaluateEffectParams()
7670
+ return true
7671
+ }
7672
+
7673
+ /**
7674
+ * Every effect's keyed dials at this transport time, then every bone and
7675
+ * followed point where it stands now — once a frame, after the schedules, so
7676
+ * each mount reads this frame's values. One upload per effect, and only for
7677
+ * one whose block moved.
7678
+ */
7679
+ private evaluateEffectParams(): void {
7680
+ let transport: number | null = null
7681
+ for (const fx of this.effects) {
7682
+ if (!fx.paramsBuffer) continue
7683
+ let dirty = false
7684
+ for (const [name, track] of fx.paramTracks) {
7685
+ transport ??= this.transportTime()
7686
+ const v = sampleParamTrack(track.keys, transport)
7687
+ if (v === null || !paramChanged(v, track.last)) continue
7688
+ track.last = v
7689
+ const decl = fx.paramDecls.find((p) => p.name === name)
7690
+ if (decl?.kind === "bone") {
7691
+ const bone = typeof v === "number" ? track.bones[v] : undefined
7692
+ if (bone) fx.paramBindings.set(name, bone)
7693
+ } else if (typeof v === "number") {
7694
+ dirty = this.writeEffectParam(fx, name, v) || dirty
7695
+ } else {
7696
+ const held = fx.paramBindings.get(name)
7697
+ const model = held && !isBoneValue(held) ? held.model : undefined
7698
+ dirty = this.writeEffectParam(fx, name, { x: v[0], y: v[1], z: v[2], ...(model ? { model } : {}) }) || dirty
7699
+ }
7700
+ }
7701
+ if (fx.paramBindings.size) dirty = this.resolveParamBindings(fx) || dirty
7702
+ if (dirty) this.device.queue.writeBuffer(fx.paramsBuffer, 0, fx.paramsData)
7524
7703
  }
7525
- this.device.queue.writeBuffer(fx.paramsBuffer, 0, fx.paramsData)
7704
+ }
7705
+
7706
+ /** Bones and followed points into the block, where they stand this frame. */
7707
+ private resolveParamBindings(fx: EffectInstance): boolean {
7708
+ const d = fx.paramsData
7709
+ let moved = false
7710
+ const put = (offset: number, x: number, y: number, z: number) => {
7711
+ if (d[offset] === x && d[offset + 1] === y && d[offset + 2] === z) return
7712
+ d[offset] = x
7713
+ d[offset + 1] = y
7714
+ d[offset + 2] = z
7715
+ moved = true
7716
+ }
7717
+ const first = () => this.castSubjectNames(fx.subjects)[0] ?? null
7718
+ for (const [name, value] of fx.paramBindings) {
7719
+ const slot = fx.paramLayout.get(name)
7720
+ if (!slot) continue
7721
+ const inst = this.modelInstances.get((value.model ?? first()) ?? "")
7722
+ if (isBoneValue(value)) {
7723
+ const fwdSlot = fx.paramLayout.get(`${name}__fwd`)
7724
+ const okSlot = fx.paramLayout.get(`${name}__ok`)
7725
+ const pos = inst?.model.getBoneWorldPosition(value.bone) ?? null
7726
+ const ok = pos ? 1 : 0
7727
+ if (okSlot && d[okSlot.offset] !== ok) {
7728
+ d[okSlot.offset] = ok
7729
+ moved = true
7730
+ }
7731
+ if (!inst || !pos) continue
7732
+ const m = inst.model
7733
+ // Model space into the world, as the cast's own anchors go.
7734
+ pos.setXYZ(pos.x * m.scale, pos.y * m.scale, pos.z * m.scale)
7735
+ Quat.rotateVecInto(m.rotation, pos, pos)
7736
+ put(slot.offset, pos.x + m.position.x, pos.y + m.position.y, pos.z + m.position.z)
7737
+ const fwd = m.getBoneWorldForward(value.bone)
7738
+ if (fwd && fwdSlot) {
7739
+ Quat.rotateVecInto(m.rotation, fwd, fwd)
7740
+ put(fwdSlot.offset, fwd.x, fwd.y, fwd.z)
7741
+ }
7742
+ } else if (inst) {
7743
+ // A followed point: the offset from where she stands.
7744
+ const m = inst.model
7745
+ put(slot.offset, m.position.x + value.x, m.position.y + value.y, m.position.z + value.z)
7746
+ }
7747
+ }
7748
+ return moved
7526
7749
  }
7527
7750
 
7528
7751
  /**
@@ -7560,6 +7783,28 @@ export class Engine {
7560
7783
  fx.influence = Math.min(1, Math.max(0, influence))
7561
7784
  }
7562
7785
 
7786
+ /**
7787
+ * Influence from keys on the transport, the way a dial is keyed: a fade in is
7788
+ * a key at 0 and a key at 1, eased by its curve. Null or no keys gives it
7789
+ * back to setEffectInfluence. It shapes the level the strips ramp toward.
7790
+ */
7791
+ setEffectInfluenceTrack(index: number, keys: readonly EffectParamKey[] | null): void {
7792
+ const fx = this.effects[index]
7793
+ if (!fx) return
7794
+ const track: ParamKey[] = []
7795
+ for (const k of keys ?? []) {
7796
+ if (typeof k.value !== "number") continue
7797
+ track.push({
7798
+ t: k.time,
7799
+ v: k.value,
7800
+ ...(k.ease ? { e: k.ease } : {}),
7801
+ ...(k.curve && k.ease !== "hold" ? { b: k.curve } : {}),
7802
+ })
7803
+ }
7804
+ track.sort((a, b) => a.t - b.t)
7805
+ fx.influenceTrack = track.length ? track : null
7806
+ }
7807
+
7563
7808
  getEffectInfluence(index: number): number {
7564
7809
  return this.effects[index]?.influence ?? 0
7565
7810
  }
@@ -7648,11 +7893,13 @@ export class Engine {
7648
7893
  const transport = this.transportTime()
7649
7894
  for (const fx of this.effects) {
7650
7895
  fx.simReset = false
7896
+ const keyed = fx.influenceTrack ? sampleParamTrack(fx.influenceTrack, transport) : null
7897
+ const level = typeof keyed === "number" ? Math.min(1, Math.max(0, keyed)) : fx.influence
7651
7898
  if (!fx.window || fx.window.length === 0) {
7652
- fx.weight = fx.influence
7899
+ fx.weight = level
7653
7900
  continue
7654
7901
  }
7655
- const at = effectState(fx.window, fx.influence, transport)
7902
+ const at = effectState(fx.window, level, transport)
7656
7903
  fx.weight = at.weight
7657
7904
  // The particles and the grid carry state from frame to frame, so they get
7658
7905
  // more than a clock: a restart on entering a window or going back in one,
@@ -15629,6 +15876,9 @@ export class Engine {
15629
15876
  objectId: (this.lastObjectId = this.lastObjectId >= GROUND_OBJECT_ID - 1 ? 1 : this.lastObjectId + 1),
15630
15877
  dissolve: 1,
15631
15878
  materialUniformBuffers: [],
15879
+ materialNames: [],
15880
+ materialDissolve: new Map(),
15881
+ dissolveWritten: [],
15632
15882
  outlineUniformBuffers: [],
15633
15883
  outlineByMaterial: new Map(),
15634
15884
  cullModelIndex: 0,
@@ -16243,6 +16493,8 @@ export class Engine {
16243
16493
  )
16244
16494
  inst.gpuBuffers.push(materialUniformBuffer)
16245
16495
  inst.materialUniformBuffers.push(materialUniformBuffer)
16496
+ inst.materialNames.push(mat.name)
16497
+ inst.dissolveWritten.push(1)
16246
16498
  if (morphedMaterials.has(pmxMaterialIndex)) {
16247
16499
  const base = this.materialUniformData(mat, sphereMode, headBoneIndex, materialId, modelId)
16248
16500
  morphTargets.push({
@@ -18071,6 +18323,9 @@ export class Engine {
18071
18323
  // caller so that playback, the export loop and a warm-up pass cannot
18072
18324
  // disagree about when an effect is alive — none of them has to remember it.
18073
18325
  this.evaluateEffectSchedules()
18326
+ // The dials' keys and the bones and points they follow, on this frame —
18327
+ // after the schedules, before anything reads an effect's block.
18328
+ this.evaluateEffectParams()
18074
18329
  this.stepSim(encoder, deltaTime)
18075
18330
  this.stepParticles(encoder, deltaTime)
18076
18331
  // Before the scene pass, which READS the slots this writes. Same buffer,
@@ -18540,31 +18795,75 @@ export class Engine {
18540
18795
  const v = Math.min(1, Math.max(0, value))
18541
18796
  if (inst.dissolve === v) return true
18542
18797
  inst.dissolve = v
18543
- // Offset 60: the sixteenth float of MaterialUniforms. One four-byte write
18544
- // per material rather than the whole block — the block only exists as a
18545
- // copy for materials that morph.
18546
- const one = new Float32Array([v])
18547
- for (const buffer of inst.materialUniformBuffers) {
18548
- this.device.queue.writeBuffer(buffer, 60, one)
18798
+ this.writeDissolve(inst)
18799
+ return true
18800
+ }
18801
+
18802
+ /**
18803
+ * Take some of one model's MATERIALS apart: the stockings, the jacket, a hat
18804
+ * — by material name, 1 whole, 0 gone. The same dissolve the whole model
18805
+ * comes apart by (setModelDissolve), with the same burning front, honoured by
18806
+ * the colour pass, the depth prepass, the shadow map and the outline; it is
18807
+ * only narrowed to the materials named. Each replaces the last set: a name
18808
+ * left out is whole again, and null makes them all whole.
18809
+ *
18810
+ * A material wears the lower of this and the model's own dissolve, so a
18811
+ * model coming apart takes these with it.
18812
+ */
18813
+ setMaterialDissolve(modelName: string, values: Readonly<Record<string, number>> | null): boolean {
18814
+ const inst = this.modelInstances.get(modelName)
18815
+ if (!inst) return false
18816
+ const next = new Map<string, number>()
18817
+ if (values) {
18818
+ for (const [name, value] of Object.entries(values)) {
18819
+ const v = Math.min(1, Math.max(0, Number.isFinite(value) ? value : 1))
18820
+ if (v < 1) next.set(name, v)
18821
+ }
18549
18822
  }
18550
- // And the hulls, which bind their own 32 bytes of edge data rather than the
18551
- // material block — so this is a different buffer at a different offset, and
18552
- // missing it left a dissolved character standing in her own outline.
18553
- for (const buffer of inst.outlineUniformBuffers) {
18554
- this.device.queue.writeBuffer(buffer, RZ_OUTLINE_DISSOLVE_OFFSET, one)
18823
+ inst.materialDissolve = next
18824
+ this.writeDissolve(inst)
18825
+ return true
18826
+ }
18827
+
18828
+ /** What setMaterialDissolve last set for one material, 1 when whole. */
18829
+ getMaterialDissolve(modelName: string, materialName: string): number {
18830
+ return this.modelInstances.get(modelName)?.materialDissolve.get(materialName) ?? 1
18831
+ }
18832
+
18833
+ /**
18834
+ * Each material's dissolve into its buffers: the lower of the model's and its
18835
+ * own. Only buffers whose value moved are written.
18836
+ *
18837
+ * Offset 60 is the sixteenth float of MaterialUniforms, which the colour pass,
18838
+ * the depth prepass and the shadow map all bind. The hulls bind their own 32
18839
+ * bytes of edge data, so they are a different buffer at a different offset —
18840
+ * missing them left a dissolved character standing in her own outline.
18841
+ */
18842
+ private writeDissolve(inst: ModelInstance): void {
18843
+ const one = new Float32Array(1)
18844
+ let moved = false
18845
+ for (let i = 0; i < inst.materialNames.length; i++) {
18846
+ const name = inst.materialNames[i]
18847
+ const v = Math.min(inst.dissolve, inst.materialDissolve.get(name) ?? 1)
18848
+ if (inst.dissolveWritten[i] === v) continue
18849
+ inst.dissolveWritten[i] = v
18850
+ moved = true
18851
+ one[0] = v
18852
+ this.device.queue.writeBuffer(inst.materialUniformBuffers[i], 60, one)
18853
+ const hull = inst.outlineByMaterial.get(name)
18854
+ if (hull) this.device.queue.writeBuffer(hull.buffer, RZ_OUTLINE_DISSOLVE_OFFSET, one)
18555
18855
  }
18556
18856
  // The morph path rebuilds a material's block from its `base` copy and
18557
18857
  // uploads it whole, which would put the old value straight back. Patching
18558
18858
  // `base` is what keeps a face that is morphing while she dissolves from
18559
18859
  // coming back solid for those frames; `last` is cleared so the next
18560
18860
  // comparison genuinely re-uploads rather than deciding nothing moved.
18561
- if (inst.materialMorphTargets) {
18861
+ if (moved && inst.materialMorphTargets) {
18562
18862
  for (const t of inst.materialMorphTargets) {
18563
- t.base[15] = v
18863
+ t.base[15] = Math.min(inst.dissolve, inst.materialDissolve.get(t.materialName) ?? 1)
18564
18864
  t.last[15] = Number.NaN
18565
18865
  }
18566
18866
  }
18567
- return true
18568
18867
  }
18569
18868
 
18570
18869
  /**
package/src/index.ts CHANGED
@@ -32,6 +32,9 @@ export {
32
32
  type GizmoDragKind,
33
33
  type DissolveCycle,
34
34
  type EffectParamValue,
35
+ type EffectPointValue,
36
+ type EffectBoneValue,
37
+ type EffectParamKey,
35
38
  type EffectResult,
36
39
  type ViewLut,
37
40
  type CullDiagnostics,
@@ -110,6 +113,7 @@ export {
110
113
  DIRECTIVE_NOTE,
111
114
  type EffectDirectives,
112
115
  type EffectParamDecl,
116
+ type EffectParamOption,
113
117
  } from "./shaders/directives"
114
118
  export {
115
119
  Model,