@hackbuild/live2d 0.0.0-stage → 0.1.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.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * A Live2D model on a canvas: the Cubism Core reads the .moc3, and this
3
+ * library plays its motions and expressions, blinks, breathes, turns toward
4
+ * a point, moves the mouth from a level, and draws it. Each frame starts
5
+ * from the parameters' defaults, then motions (crossfaded), the expression,
6
+ * the blink, breath, look and mouth, then any value set by hand, clamped to
7
+ * each parameter's range. Physics (.physics3.json) is not run.
8
+ */
9
+ import { type CoreOptions, type CubismCore } from "./core.js";
10
+ import type { ModelSource } from "./files.js";
11
+ /** How much of the model the canvas shows: all of it, or the head and shoulders. */
12
+ export type Live2DFrame = "full" | "bust";
13
+ /** Options for {@link createLive2D}. */
14
+ export interface Live2DOptions extends CoreOptions {
15
+ /** A core already loaded; default {@link loadCubismCore}. */
16
+ core?: CubismCore;
17
+ /** Default "full". */
18
+ frame?: Live2DFrame;
19
+ /** Idle motions, blink and breath on their own. Default true. */
20
+ autoplay?: boolean;
21
+ /** Run its own animation frame loop. Default true; false means you call `update(dt)`. */
22
+ loop?: boolean;
23
+ /** 0 to 1, for blink timing and idle picks. Default a seeded generator. */
24
+ rng?: () => number;
25
+ }
26
+ /** A model on a canvas, with its controls. */
27
+ export interface Live2DModel {
28
+ readonly name: string;
29
+ readonly coreVersion: string;
30
+ /** Expression names from the settings. */
31
+ readonly expressions: string[];
32
+ /** Motion groups and how many motions each holds that loaded. */
33
+ readonly motions: Record<string, number>;
34
+ /** Parameter ids. */
35
+ readonly parameters: string[];
36
+ /** Files the settings name that the source did not hold. */
37
+ readonly missing: string[];
38
+ /** Fades to an expression by name, or back to none. */
39
+ expression(name: string | null): boolean;
40
+ /** Plays a motion of a group, by index or at random; returns false when the group has none. */
41
+ motion(group: string, index?: number): boolean;
42
+ /** The mouth, 0 shut to 1 open, as from a lip sync level. */
43
+ mouth(open: number): void;
44
+ /** Where to look, x and y from -1 to 1 (right and up are positive). */
45
+ look(x: number, y: number): void;
46
+ /** Holds a parameter at a value until set to null. */
47
+ set(id: string, value: number | null): void;
48
+ frame(mode: Live2DFrame): void;
49
+ /** Matches the drawing buffer to the canvas's size on screen. */
50
+ resize(): void;
51
+ /** Advances by dt seconds and draws; the own loop calls it. */
52
+ update(dt: number): void;
53
+ dispose(): void;
54
+ }
55
+ /** Opens a model source on a canvas and starts it. */
56
+ export declare function createLive2D(canvas: HTMLCanvasElement, source: ModelSource, o?: Live2DOptions): Promise<Live2DModel>;
package/dist/model.js ADDED
@@ -0,0 +1,269 @@
1
+ /**
2
+ * A Live2D model on a canvas: the Cubism Core reads the .moc3, and this
3
+ * library plays its motions and expressions, blinks, breathes, turns toward
4
+ * a point, moves the mouth from a level, and draws it. Each frame starts
5
+ * from the parameters' defaults, then motions (crossfaded), the expression,
6
+ * the blink, breath, look and mouth, then any value set by hand, clamped to
7
+ * each parameter's range. Physics (.physics3.json) is not run.
8
+ */
9
+ import { coreVersion, loadCubismCore, Live2DError } from "./core.js";
10
+ import { Blinker, blendExpression, ease, parseExpression, parseMotion, sampleMotion } from "./motion.js";
11
+ import { fitMatrix, modelBounds, Renderer } from "./render.js";
12
+ function seeded(seed = 0x2f6b) {
13
+ let a = seed >>> 0;
14
+ return () => {
15
+ a = (a + 0x6d2b79f5) >>> 0;
16
+ let t = a;
17
+ t = Math.imul(t ^ (t >>> 15), t | 1);
18
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
19
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
20
+ };
21
+ }
22
+ // the breath, as sine sways on the standard parameter ids: offset, peak, cycle in seconds
23
+ const BREATH = [
24
+ ["ParamAngleX", 0, 15, 6.5345],
25
+ ["ParamAngleY", 0, 8, 3.5345],
26
+ ["ParamAngleZ", 0, 10, 5.5345],
27
+ ["ParamBodyAngleX", 0, 4, 15.5345],
28
+ ["ParamBreath", 0.5, 0.5, 3.2345],
29
+ ];
30
+ /** Opens a model source on a canvas and starts it. */
31
+ export async function createLive2D(canvas, source, o = {}) {
32
+ const gl = canvas.getContext("webgl", { stencil: true, premultipliedAlpha: true, alpha: true, antialias: true });
33
+ if (!gl)
34
+ throw new Live2DError("this browser gives no webgl here. live2d models draw with webgl.");
35
+ const core = o.core ?? (await loadCubismCore(o));
36
+ const consistent = core.Moc.hasMocConsistency;
37
+ if (consistent && !consistent(source.moc))
38
+ throw new Live2DError(`the cubism core ${coreVersion(core)} could not check ${source.name}.moc3: it is damaged or newer than the core.`);
39
+ const moc = core.Moc.fromArrayBuffer(source.moc);
40
+ if (!moc)
41
+ throw new Live2DError(`the cubism core ${coreVersion(core)} could not read ${source.name}.moc3: it may be newer than the core.`);
42
+ const made = core.Model.fromMoc(moc);
43
+ if (!made)
44
+ throw new Live2DError(`the cubism core could not make a model from ${source.name}.moc3.`);
45
+ const model = made;
46
+ const renderer = new Renderer(gl, core, model);
47
+ await renderer.textures(source.textures);
48
+ const P = model.parameters;
49
+ const index = new Map(P.ids.map((id, i) => [id, i]));
50
+ const defaults = Float32Array.from(P.defaultValues);
51
+ const has = (id) => index.has(id);
52
+ const group = (name) => source.settings.Groups?.find((g) => g.Name === name)?.Ids.filter(has) ?? [];
53
+ const eyes = group("EyeBlink").length ? group("EyeBlink") : ["ParamEyeLOpen", "ParamEyeROpen"].filter(has);
54
+ const lips = group("LipSync").length ? group("LipSync") : ["ParamMouthOpenY"].filter(has);
55
+ const motions = new Map();
56
+ for (const m of source.motions) {
57
+ if (!m.json)
58
+ continue;
59
+ const list = motions.get(m.group) ?? [];
60
+ list.push(parseMotion(m.json, { ...(m.fadeIn !== undefined ? { fadeIn: m.fadeIn } : {}), ...(m.fadeOut !== undefined ? { fadeOut: m.fadeOut } : {}) }));
61
+ motions.set(m.group, list);
62
+ }
63
+ const expressions = new Map(source.expressions.map((e) => [e.name, parseExpression(e.json)]));
64
+ const idleGroup = [...motions.keys()].find((g) => /idle/i.test(g)) ?? null;
65
+ // pose: in each group one part shows; the first at the start, then whichever a motion raises
66
+ const partIndex = new Map(model.parts.ids.map((id, i) => [id, i]));
67
+ const poseGroups = (source.pose?.Groups ?? [])
68
+ .map((g) => g.map((p) => partIndex.get(p.Id)).filter((i) => i !== undefined))
69
+ .filter((g) => g.length > 1);
70
+ const shown = poseGroups.map((g) => g[0]);
71
+ const rng = o.rng ?? seeded();
72
+ const auto = o.autoplay !== false;
73
+ const blink = new Blinker(rng);
74
+ const holds = new Map();
75
+ let now = 0;
76
+ let cur = null;
77
+ let prev = null;
78
+ let exp = null;
79
+ let expOut = null;
80
+ let mouthOpen = 0;
81
+ const lookAt = { x: 0, y: 0, sx: 0, sy: 0 };
82
+ let frameMode = o.frame ?? "full";
83
+ let matrix = null;
84
+ let box = null;
85
+ const add = (id, v) => {
86
+ const i = index.get(id);
87
+ if (i !== undefined)
88
+ P.values[i] += v;
89
+ };
90
+ function play(group, i) {
91
+ const list = motions.get(group);
92
+ if (!list?.length)
93
+ return false;
94
+ const m = list[i ?? Math.floor(rng() * list.length)] ?? list[0];
95
+ if (cur)
96
+ prev = { ...cur, outAt: cur.outAt ?? now - cur.start };
97
+ cur = { m, start: now, outAt: null };
98
+ return true;
99
+ }
100
+ function step(dt) {
101
+ now += dt;
102
+ P.values.set(defaults);
103
+ if (auto && !cur && idleGroup)
104
+ play(idleGroup);
105
+ if (cur && !cur.m.loop && cur.outAt === null && now - cur.start >= Math.max(cur.m.duration - cur.m.fadeOut, 0))
106
+ cur.outAt = now - cur.start;
107
+ if (cur && cur.outAt !== null && now - cur.start - cur.outAt >= cur.m.fadeOut) {
108
+ prev = null;
109
+ cur = null;
110
+ if (auto && idleGroup)
111
+ play(idleGroup);
112
+ }
113
+ if (prev && prev.outAt !== null && now - prev.start - prev.outAt >= prev.m.fadeOut)
114
+ prev = null;
115
+ let eyeFactor = 1;
116
+ let lipFactor = 1;
117
+ for (const p of [prev, cur]) {
118
+ if (!p)
119
+ continue;
120
+ const f = sampleMotion(p.m, now - p.start, 1, p.outAt);
121
+ for (const [id, { value, weight }] of f.params) {
122
+ const k = index.get(id);
123
+ if (k !== undefined)
124
+ P.values[k] = P.values[k] * (1 - weight) + value * weight;
125
+ }
126
+ for (const [id, v] of f.parts) {
127
+ const k = partIndex.get(id);
128
+ if (k === undefined)
129
+ continue;
130
+ model.parts.opacities[k] = v;
131
+ poseGroups.forEach((g, gi) => { if (g.includes(k) && v > 0.5)
132
+ shown[gi] = k; });
133
+ }
134
+ if (f.groups.has("EyeBlink"))
135
+ eyeFactor = f.groups.get("EyeBlink");
136
+ if (f.groups.has("LipSync"))
137
+ lipFactor = f.groups.get("LipSync");
138
+ }
139
+ poseGroups.forEach((g, gi) => { for (const k of g)
140
+ model.parts.opacities[k] = k === shown[gi] ? 1 : 0; });
141
+ for (const [x, w] of [[expOut, -1], [exp, 1]]) {
142
+ if (!x)
143
+ continue;
144
+ const t = now - x.start;
145
+ const weight = w > 0 ? ease(x.e.fadeIn > 0 ? t / x.e.fadeIn : 1) : 1 - ease(x.e.fadeOut > 0 ? t / x.e.fadeOut : 1);
146
+ if (w < 0 && weight <= 0) {
147
+ expOut = null;
148
+ continue;
149
+ }
150
+ for (const p of x.e.params) {
151
+ const k = index.get(p.id);
152
+ if (k !== undefined)
153
+ P.values[k] = blendExpression(P.values[k], p, weight);
154
+ }
155
+ }
156
+ if (auto) {
157
+ const open = blink.open(now);
158
+ for (const id of eyes) {
159
+ const k = index.get(id);
160
+ P.values[k] = P.values[k] * (1 - (1 - open) * eyeFactor);
161
+ }
162
+ for (const [id, off, peak, cycle] of BREATH)
163
+ add(id, (off + peak * Math.sin((2 * Math.PI * now) / cycle)) * 0.5);
164
+ }
165
+ const k = 1 - Math.exp(-dt * 8);
166
+ lookAt.sx += (lookAt.x - lookAt.sx) * k;
167
+ lookAt.sy += (lookAt.y - lookAt.sy) * k;
168
+ add("ParamAngleX", lookAt.sx * 30);
169
+ add("ParamAngleY", lookAt.sy * 30);
170
+ add("ParamAngleZ", lookAt.sx * lookAt.sy * -30);
171
+ add("ParamBodyAngleX", lookAt.sx * 10);
172
+ add("ParamEyeBallX", lookAt.sx);
173
+ add("ParamEyeBallY", lookAt.sy);
174
+ for (const id of lips)
175
+ add(id, mouthOpen * 0.8 * lipFactor);
176
+ for (const [i, v] of holds)
177
+ P.values[i] = v;
178
+ for (let i = 0; i < P.count; i++)
179
+ P.values[i] = Math.min(P.maximumValues[i], Math.max(P.minimumValues[i], P.values[i]));
180
+ model.update();
181
+ }
182
+ function sizeCanvas() {
183
+ const dpr = Math.min(2, globalThis.devicePixelRatio || 1);
184
+ const w = Math.max(1, Math.round((canvas.clientWidth || canvas.width) * dpr));
185
+ const h = Math.max(1, Math.round((canvas.clientHeight || canvas.height) * dpr));
186
+ if (canvas.width !== w || canvas.height !== h) {
187
+ canvas.width = w;
188
+ canvas.height = h;
189
+ }
190
+ matrix = null;
191
+ }
192
+ function draw() {
193
+ if (!box)
194
+ box = modelBounds(model, core);
195
+ if (!matrix) {
196
+ const b = frameMode === "bust" ? { ...box, minY: box.maxY - (box.maxY - box.minY) * 0.5 } : box;
197
+ matrix = fitMatrix(b, canvas.width, canvas.height);
198
+ }
199
+ gl.viewport(0, 0, canvas.width, canvas.height);
200
+ gl.clearColor(0, 0, 0, 0);
201
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
202
+ renderer.draw(matrix);
203
+ model.drawables.resetDynamicFlags();
204
+ }
205
+ sizeCanvas();
206
+ step(0);
207
+ draw();
208
+ let raf = 0;
209
+ let last = 0;
210
+ let gone = false;
211
+ const tick = (t) => {
212
+ if (gone)
213
+ return;
214
+ const dt = last ? Math.min(0.1, (t - last) / 1000) : 1 / 60;
215
+ last = t;
216
+ step(dt);
217
+ draw();
218
+ raf = requestAnimationFrame(tick);
219
+ };
220
+ if (o.loop !== false && typeof requestAnimationFrame === "function")
221
+ raf = requestAnimationFrame(tick);
222
+ const groups = {};
223
+ for (const [g, l] of motions)
224
+ groups[g] = l.length;
225
+ return {
226
+ name: source.name,
227
+ coreVersion: coreVersion(core),
228
+ expressions: [...expressions.keys()],
229
+ motions: groups,
230
+ parameters: [...P.ids],
231
+ missing: [...source.missing],
232
+ expression(name) {
233
+ if (name === null) {
234
+ if (exp)
235
+ expOut = { e: exp.e, start: now };
236
+ exp = null;
237
+ return true;
238
+ }
239
+ const e = expressions.get(name);
240
+ if (!e)
241
+ return false;
242
+ if (exp)
243
+ expOut = { e: exp.e, start: now };
244
+ exp = { e, start: now };
245
+ return true;
246
+ },
247
+ motion: play,
248
+ mouth(v) { mouthOpen = Math.min(1, Math.max(0, v)); },
249
+ look(x, y) { lookAt.x = Math.min(1, Math.max(-1, x)); lookAt.y = Math.min(1, Math.max(-1, y)); },
250
+ set(id, v) {
251
+ const i = index.get(id);
252
+ if (i === undefined)
253
+ return;
254
+ if (v === null)
255
+ holds.delete(i);
256
+ else
257
+ holds.set(i, v);
258
+ },
259
+ frame(mode) { frameMode = mode; matrix = null; },
260
+ resize: sizeCanvas,
261
+ update(dt) { step(dt); draw(); },
262
+ dispose() {
263
+ gone = true;
264
+ cancelAnimationFrame(raf);
265
+ renderer.dispose();
266
+ model.release();
267
+ },
268
+ };
269
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Live2D motions (.motion3.json) and expressions (.exp3.json), written from
3
+ * the published file formats: a motion is curves of points joined by linear,
4
+ * bezier, stepped or inverse stepped segments, aimed at a parameter, a part's
5
+ * opacity or a model group (eye blink, lip sync), with fades in and out. An
6
+ * expression adds, multiplies or overwrites parameters. Pure functions of
7
+ * time, so they test without the Cubism Core.
8
+ */
9
+ /** A curve's target kind. */
10
+ export type CurveTarget = "Parameter" | "PartOpacity" | "Model";
11
+ interface Seg {
12
+ type: 0 | 1 | 2 | 3;
13
+ /** Points: start, then the segment's own (controls for a bezier, then its end). */
14
+ p: number[];
15
+ }
16
+ /** One curve: its target, id, optional own fades and its segments. */
17
+ export interface Curve {
18
+ target: CurveTarget;
19
+ id: string;
20
+ fadeIn: number | null;
21
+ fadeOut: number | null;
22
+ t0: number;
23
+ v0: number;
24
+ segs: Seg[];
25
+ }
26
+ /** A parsed motion. */
27
+ export interface Motion {
28
+ duration: number;
29
+ loop: boolean;
30
+ fadeIn: number;
31
+ fadeOut: number;
32
+ restricted: boolean;
33
+ curves: Curve[];
34
+ }
35
+ /** Parses a .motion3.json; fades default to the motion's own, then the model's entry, then 1 s and 1 s. */
36
+ export declare function parseMotion(json: unknown, o?: {
37
+ fadeIn?: number;
38
+ fadeOut?: number;
39
+ }): Motion;
40
+ /** A curve's value at time t (seconds); before its first point the first value, after its last the last. */
41
+ export declare function curveValue(c: Curve, t: number, restricted?: boolean): number;
42
+ /** Cubism's fade curve: a half cosine from 0 to 1. */
43
+ export declare const ease: (x: number) => number;
44
+ /** What a motion asks for at one moment: parameter values, part opacities and group factors, each with its weight. */
45
+ export interface MotionFrame {
46
+ params: Map<string, {
47
+ value: number;
48
+ weight: number;
49
+ }>;
50
+ parts: Map<string, number>;
51
+ /** Factors for model groups: EyeBlink, LipSync. */
52
+ groups: Map<string, number>;
53
+ }
54
+ /**
55
+ * Samples a motion `elapsed` seconds after it started, with an overall weight;
56
+ * `outAt` is when its fade out began (seconds after start), or null.
57
+ */
58
+ export declare function sampleMotion(m: Motion, elapsed: number, weight?: number, outAt?: number | null): MotionFrame;
59
+ /** How an expression parameter blends. */
60
+ export type ExpressionBlend = "Add" | "Multiply" | "Overwrite";
61
+ /** A parsed expression. */
62
+ export interface Expression {
63
+ fadeIn: number;
64
+ fadeOut: number;
65
+ params: {
66
+ id: string;
67
+ value: number;
68
+ blend: ExpressionBlend;
69
+ }[];
70
+ }
71
+ /** Parses a .exp3.json; fades default to 1 s. */
72
+ export declare function parseExpression(json: unknown): Expression;
73
+ /** One parameter value with an expression applied at weight w. */
74
+ export declare function blendExpression(current: number, p: {
75
+ value: number;
76
+ blend: ExpressionBlend;
77
+ }, w: number): number;
78
+ /**
79
+ * An eye blink in the rhythm people blink: open, then about every 2 to 6 s a
80
+ * close of 0.1 s, a hold of 0.05 s and an open of 0.15 s (inferred from
81
+ * blink studies). Returns the eye openness, 1 open to 0 shut. `rng` is 0 to 1.
82
+ */
83
+ export declare class Blinker {
84
+ private rng;
85
+ private next;
86
+ private start;
87
+ constructor(rng: () => number, now?: number);
88
+ open(now: number): number;
89
+ }
90
+ export {};
package/dist/motion.js ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Live2D motions (.motion3.json) and expressions (.exp3.json), written from
3
+ * the published file formats: a motion is curves of points joined by linear,
4
+ * bezier, stepped or inverse stepped segments, aimed at a parameter, a part's
5
+ * opacity or a model group (eye blink, lip sync), with fades in and out. An
6
+ * expression adds, multiplies or overwrites parameters. Pure functions of
7
+ * time, so they test without the Cubism Core.
8
+ */
9
+ /** Parses a .motion3.json; fades default to the motion's own, then the model's entry, then 1 s and 1 s. */
10
+ export function parseMotion(json, o = {}) {
11
+ const j = (json ?? {});
12
+ const meta = (j.Meta ?? {});
13
+ const curves = [];
14
+ for (const c of (j.Curves ?? [])) {
15
+ const s = (c.Segments ?? []);
16
+ if (s.length < 2)
17
+ continue;
18
+ const segs = [];
19
+ let i = 2;
20
+ let lastT = s[0];
21
+ let lastV = s[1];
22
+ while (i < s.length) {
23
+ const type = s[i];
24
+ const n = type === 1 ? 6 : 2;
25
+ const pts = s.slice(i + 1, i + 1 + n);
26
+ if (pts.length < n)
27
+ break;
28
+ segs.push({ type, p: [lastT, lastV, ...pts] });
29
+ lastT = pts[n - 2];
30
+ lastV = pts[n - 1];
31
+ i += 1 + n;
32
+ }
33
+ curves.push({
34
+ target: c.Target ?? "Parameter",
35
+ id: String(c.Id ?? ""),
36
+ fadeIn: typeof c.FadeInTime === "number" && c.FadeInTime >= 0 ? c.FadeInTime : null,
37
+ fadeOut: typeof c.FadeOutTime === "number" && c.FadeOutTime >= 0 ? c.FadeOutTime : null,
38
+ t0: s[0],
39
+ v0: s[1],
40
+ segs,
41
+ });
42
+ }
43
+ const num = (v, d) => (typeof v === "number" && v >= 0 ? v : d);
44
+ return {
45
+ duration: num(meta.Duration, 0),
46
+ loop: meta.Loop === true,
47
+ fadeIn: num(meta.FadeInTime, o.fadeIn ?? 1),
48
+ fadeOut: num(meta.FadeOutTime, o.fadeOut ?? 1),
49
+ restricted: meta.AreBeziersRestricted === true,
50
+ curves,
51
+ };
52
+ }
53
+ const lerp = (a, b, t) => a + (b - a) * t;
54
+ function bez(a, b, c, d, s) {
55
+ const ab = lerp(a, b, s), bc = lerp(b, c, s), cd = lerp(c, d, s);
56
+ return lerp(lerp(ab, bc, s), lerp(bc, cd, s), s);
57
+ }
58
+ /** A curve's value at time t (seconds); before its first point the first value, after its last the last. */
59
+ export function curveValue(c, t, restricted = false) {
60
+ if (!c.segs.length || t <= c.t0)
61
+ return c.v0;
62
+ for (const s of c.segs) {
63
+ const p = s.p;
64
+ const t0 = p[0], v0 = p[1];
65
+ const t1 = p[p.length - 2], v1 = p[p.length - 1];
66
+ if (t > t1)
67
+ continue;
68
+ const x = t1 > t0 ? (t - t0) / (t1 - t0) : 1;
69
+ if (s.type === 0)
70
+ return lerp(v0, v1, x);
71
+ if (s.type === 2)
72
+ return t < t1 ? v0 : v1;
73
+ if (s.type === 3)
74
+ return t > t0 ? v1 : v0;
75
+ // bezier: restricted curves use x as the parameter; free ones solve x(s) = t by bisection
76
+ const [, , c1t, c1v, c2t, c2v] = p;
77
+ if (restricted)
78
+ return bez(v0, c1v, c2v, v1, x);
79
+ let lo = 0, hi = 1, sp = x;
80
+ for (let k = 0; k < 24; k++) {
81
+ sp = (lo + hi) / 2;
82
+ if (bez(t0, c1t, c2t, t1, sp) < t)
83
+ lo = sp;
84
+ else
85
+ hi = sp;
86
+ }
87
+ return bez(v0, c1v, c2v, v1, sp);
88
+ }
89
+ const last = c.segs[c.segs.length - 1].p;
90
+ return last[last.length - 1];
91
+ }
92
+ /** Cubism's fade curve: a half cosine from 0 to 1. */
93
+ export const ease = (x) => (x <= 0 ? 0 : x >= 1 ? 1 : 0.5 - 0.5 * Math.cos(x * Math.PI));
94
+ /**
95
+ * Samples a motion `elapsed` seconds after it started, with an overall weight;
96
+ * `outAt` is when its fade out began (seconds after start), or null.
97
+ */
98
+ export function sampleMotion(m, elapsed, weight = 1, outAt = null) {
99
+ const t = m.loop && m.duration > 0 ? elapsed % m.duration : Math.min(elapsed, m.duration || elapsed);
100
+ const fadeIn = (f) => (f > 0 ? ease(elapsed / f) : 1);
101
+ const fadeOut = (f) => (outAt === null ? 1 : f > 0 ? 1 - ease((elapsed - outAt) / f) : 0);
102
+ const base = weight * fadeIn(m.fadeIn) * fadeOut(m.fadeOut);
103
+ const out = { params: new Map(), parts: new Map(), groups: new Map() };
104
+ for (const c of m.curves) {
105
+ const v = curveValue(c, t, m.restricted);
106
+ if (c.target === "Parameter") {
107
+ const w = c.fadeIn === null && c.fadeOut === null ? base : weight * fadeIn(c.fadeIn ?? m.fadeIn) * fadeOut(c.fadeOut ?? m.fadeOut);
108
+ out.params.set(c.id, { value: v, weight: w });
109
+ }
110
+ else if (c.target === "PartOpacity")
111
+ out.parts.set(c.id, v);
112
+ else
113
+ out.groups.set(c.id, v);
114
+ }
115
+ return out;
116
+ }
117
+ /** Parses a .exp3.json; fades default to 1 s. */
118
+ export function parseExpression(json) {
119
+ const j = (json ?? {});
120
+ const num = (v, d) => (typeof v === "number" && v >= 0 ? v : d);
121
+ return {
122
+ fadeIn: num(j.FadeInTime, 1),
123
+ fadeOut: num(j.FadeOutTime, 1),
124
+ params: (j.Parameters ?? []).map((p) => ({
125
+ id: String(p.Id),
126
+ value: Number(p.Value ?? 0),
127
+ blend: (p.Blend === "Multiply" || p.Blend === "Overwrite" ? p.Blend : "Add"),
128
+ })),
129
+ };
130
+ }
131
+ /** One parameter value with an expression applied at weight w. */
132
+ export function blendExpression(current, p, w) {
133
+ if (p.blend === "Add")
134
+ return current + p.value * w;
135
+ if (p.blend === "Multiply")
136
+ return current * (1 + (p.value - 1) * w);
137
+ return current * (1 - w) + p.value * w;
138
+ }
139
+ /**
140
+ * An eye blink in the rhythm people blink: open, then about every 2 to 6 s a
141
+ * close of 0.1 s, a hold of 0.05 s and an open of 0.15 s (inferred from
142
+ * blink studies). Returns the eye openness, 1 open to 0 shut. `rng` is 0 to 1.
143
+ */
144
+ export class Blinker {
145
+ rng;
146
+ next;
147
+ start = -1;
148
+ constructor(rng, now = 0) {
149
+ this.rng = rng;
150
+ this.next = now + 2 + rng() * 4;
151
+ }
152
+ open(now) {
153
+ if (this.start < 0 && now >= this.next)
154
+ this.start = now;
155
+ if (this.start < 0)
156
+ return 1;
157
+ const t = now - this.start;
158
+ if (t < 0.1)
159
+ return 1 - t / 0.1;
160
+ if (t < 0.15)
161
+ return 0;
162
+ if (t < 0.3)
163
+ return (t - 0.15) / 0.15;
164
+ this.start = -1;
165
+ this.next = now + 2 + this.rng() * 4;
166
+ return 1;
167
+ }
168
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * A WebGL renderer for a Cubism model's drawables, written for this library:
3
+ * each drawable is a textured mesh drawn in the model's render order with
4
+ * its opacity, its multiply and screen colours, and one of the three Cubism
5
+ * blend modes (normal, additive, multiplicative) on premultiplied alpha. A
6
+ * drawable with clipping masks is drawn through the stencil buffer: its mask
7
+ * meshes write the stencil where their alpha passes half, and the drawable
8
+ * draws where the stencil is set, or where it is not for an inverted mask.
9
+ */
10
+ import type { CoreModel, CubismCore } from "./core.js";
11
+ /** Where the model sits in the canvas: model units to clip space, as a 3 by 3 column major matrix. */
12
+ export type Mat3 = Float32Array;
13
+ /** Draws one Cubism model into a WebGL context that has a stencil buffer. */
14
+ export declare class Renderer {
15
+ private gl;
16
+ private core;
17
+ private model;
18
+ private prog;
19
+ private pos;
20
+ private uv;
21
+ private idx;
22
+ private tex;
23
+ private loc;
24
+ private aPos;
25
+ private aUv;
26
+ private order;
27
+ constructor(gl: WebGLRenderingContext, core: CubismCore, model: CoreModel);
28
+ /** Uploads the model's textures, premultiplied, with mipmaps. */
29
+ textures(images: Blob[]): Promise<void>;
30
+ private mesh;
31
+ /** Draws the model with the matrix; the caller has run `model.update()`. */
32
+ draw(m: Mat3): void;
33
+ dispose(): void;
34
+ }
35
+ /** The bounds of the model's visible vertices, in model units. */
36
+ export declare function modelBounds(model: CoreModel, core: CubismCore): {
37
+ minX: number;
38
+ minY: number;
39
+ maxX: number;
40
+ maxY: number;
41
+ };
42
+ /** A matrix fitting a box of model units into a canvas of w by h pixels, keeping the aspect, with a margin. */
43
+ export declare function fitMatrix(box: {
44
+ minX: number;
45
+ minY: number;
46
+ maxX: number;
47
+ maxY: number;
48
+ }, w: number, h: number, margin?: number): Mat3;