untitled-pixi-live2d-engine 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4203 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __pow = Math.pow;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ var __async = (__this, __arguments, generator) => {
6
+ return new Promise((resolve, reject) => {
7
+ var fulfilled = (value) => {
8
+ try {
9
+ step(generator.next(value));
10
+ } catch (e) {
11
+ reject(e);
12
+ }
13
+ };
14
+ var rejected = (value) => {
15
+ try {
16
+ step(generator.throw(value));
17
+ } catch (e) {
18
+ reject(e);
19
+ }
20
+ };
21
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
22
+ step((generator = generator.apply(__this, __arguments)).next());
23
+ });
24
+ };
25
+ import { EventEmitter, Matrix, loadTextures, Assets, Ticker, Transform, Point, Bounds, Container, ObservablePoint, WebGLRenderer } from "pixi.js";
26
+ import { sound, Sound, webaudio } from "@pixi/sound";
27
+ const LOGICAL_WIDTH = 2;
28
+ const LOGICAL_HEIGHT = 2;
29
+ const CSM_LOG_LEVEL_VERBOSE = 0;
30
+ const CSM_LOG_LEVEL_DEBUG = 1;
31
+ const CSM_LOG_LEVEL_INFO = 2;
32
+ const CSM_LOG_LEVEL_WARNING = 3;
33
+ const CSM_LOG_LEVEL_ERROR = 4;
34
+ const CSM_LOG_LEVEL_OFF = 5;
35
+ const CSM_LOG_LEVEL = CSM_LOG_LEVEL_VERBOSE;
36
+ const CubismFrameworkConfig = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
37
+ __proto__: null,
38
+ CSM_LOG_LEVEL,
39
+ CSM_LOG_LEVEL_DEBUG,
40
+ CSM_LOG_LEVEL_ERROR,
41
+ CSM_LOG_LEVEL_INFO,
42
+ CSM_LOG_LEVEL_OFF,
43
+ CSM_LOG_LEVEL_VERBOSE,
44
+ CSM_LOG_LEVEL_WARNING
45
+ }, Symbol.toStringTag, { value: "Module" }));
46
+ const LOG_LEVEL_VERBOSE = 0;
47
+ const LOG_LEVEL_WARNING = 1;
48
+ const LOG_LEVEL_ERROR = 2;
49
+ const LOG_LEVEL_NONE = 999;
50
+ const config = {
51
+ LOG_LEVEL_VERBOSE,
52
+ LOG_LEVEL_WARNING,
53
+ LOG_LEVEL_ERROR,
54
+ LOG_LEVEL_NONE,
55
+ /**
56
+ * Global log level.
57
+ * @default config.LOG_LEVEL_WARNING
58
+ */
59
+ logLevel: LOG_LEVEL_WARNING,
60
+ /**
61
+ * Enabling sound for motions.
62
+ */
63
+ sound: true,
64
+ /**
65
+ * fftSize for sound analyzer for lipsync.
66
+ * Must be a power of 2 between 2^5 and 2^15, so one of: 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, and 32768.
67
+ * @default 512
68
+ */
69
+ fftSize: 512,
70
+ /**
71
+ * Deferring motion and corresponding sound until both are loaded.
72
+ */
73
+ motionSync: true,
74
+ /**
75
+ * Default fading duration for motions without such value specified.
76
+ */
77
+ motionFadingDuration: 500,
78
+ /**
79
+ * Default fading duration for idle motions without such value specified.
80
+ */
81
+ idleMotionFadingDuration: 2e3,
82
+ /**
83
+ * Default fading duration for expressions without such value specified.
84
+ */
85
+ expressionFadingDuration: 500,
86
+ /**
87
+ * If false, expression will be reset to default when playing non-idle motions.
88
+ */
89
+ preserveExpressionOnMotion: true,
90
+ cubism: CubismFrameworkConfig
91
+ };
92
+ const VERSION = "1.0.0-rc.1";
93
+ const logger = {
94
+ log(tag, ...messages) {
95
+ if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
96
+ console.log(`[${tag}]`, ...messages);
97
+ }
98
+ },
99
+ warn(tag, ...messages) {
100
+ if (config.logLevel <= config.LOG_LEVEL_WARNING) {
101
+ console.warn(`[${tag}]`, ...messages);
102
+ }
103
+ },
104
+ error(tag, ...messages) {
105
+ if (config.logLevel <= config.LOG_LEVEL_ERROR) {
106
+ console.error(`[${tag}]`, ...messages);
107
+ }
108
+ }
109
+ };
110
+ function clamp(num, lower, upper) {
111
+ return num < lower ? lower : num > upper ? upper : num;
112
+ }
113
+ function rand(min, max) {
114
+ return Math.random() * (max - min) + min;
115
+ }
116
+ function MBToByte(value) {
117
+ return value * 1024 * 1024;
118
+ }
119
+ function copyProperty(type, from, to, fromKey, toKey) {
120
+ const value = from[fromKey];
121
+ if (value !== null && typeof value === type) {
122
+ to[toKey] = value;
123
+ }
124
+ }
125
+ function copyArray(type, from, to, fromKey, toKey) {
126
+ const array = from[fromKey];
127
+ if (Array.isArray(array)) {
128
+ to[toKey] = array.filter(
129
+ (item) => item !== null && typeof item === type
130
+ );
131
+ }
132
+ }
133
+ function applyMixins(derivedCtor, baseCtors) {
134
+ baseCtors.forEach((baseCtor) => {
135
+ Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
136
+ if (name !== "constructor") {
137
+ Object.defineProperty(
138
+ derivedCtor.prototype,
139
+ name,
140
+ Object.getOwnPropertyDescriptor(baseCtor.prototype, name)
141
+ );
142
+ }
143
+ });
144
+ });
145
+ }
146
+ function folderName(url) {
147
+ let lastSlashIndex = url.lastIndexOf("/");
148
+ if (lastSlashIndex != -1) {
149
+ url = url.slice(0, lastSlashIndex);
150
+ }
151
+ lastSlashIndex = url.lastIndexOf("/");
152
+ if (lastSlashIndex !== -1) {
153
+ url = url.slice(lastSlashIndex + 1);
154
+ }
155
+ return url;
156
+ }
157
+ function remove(array, item) {
158
+ const index = array.indexOf(item);
159
+ if (index !== -1) {
160
+ array.splice(index, 1);
161
+ }
162
+ }
163
+ const SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
164
+ function resolveURL(base, path) {
165
+ if (!path) {
166
+ return base;
167
+ }
168
+ if (SCHEME_RE.test(path)) {
169
+ return path;
170
+ }
171
+ if (path.startsWith("/")) {
172
+ return SCHEME_RE.test(base) ? new URL(path, base).toString() : path;
173
+ }
174
+ if (SCHEME_RE.test(base)) {
175
+ return new URL(path, base).toString();
176
+ }
177
+ const dummyOrigin = "http://example.com";
178
+ const baseForURL = base.startsWith("/") ? dummyOrigin + base : `${dummyOrigin}/${base}`;
179
+ const resolved = new URL(path, baseForURL);
180
+ let result = resolved.pathname + resolved.search + resolved.hash;
181
+ if (!base.startsWith("/") && result.startsWith("/")) {
182
+ result = result.slice(1);
183
+ }
184
+ return result;
185
+ }
186
+ class ExpressionManager extends EventEmitter {
187
+ constructor(settings, _options) {
188
+ super();
189
+ /**
190
+ * Indicates the content type used when loading expressions.
191
+ * @default "json"
192
+ */
193
+ __publicField(this, "expressionDataType", "json");
194
+ /**
195
+ * Tag for logging.
196
+ */
197
+ __publicField(this, "tag");
198
+ /**
199
+ * The ModelSettings reference.
200
+ */
201
+ __publicField(this, "settings");
202
+ /**
203
+ * The Expressions. The structure is the same as {@link definitions}, initially there's only
204
+ * an empty array, which means all expressions will be `undefined`. When an Expression has
205
+ * been loaded, it'll fill the place in which it should be; when it fails to load,
206
+ * the place will be filled with `null`.
207
+ */
208
+ __publicField(this, "expressions", []);
209
+ /**
210
+ * An empty Expression to reset all the expression parameters.
211
+ */
212
+ __publicField(this, "defaultExpression");
213
+ /**
214
+ * Current Expression. This will not be overwritten by {@link ExpressionManager#defaultExpression}.
215
+ */
216
+ __publicField(this, "currentExpression");
217
+ /**
218
+ * The pending Expression.
219
+ */
220
+ __publicField(this, "reserveExpressionIndex", -1);
221
+ /**
222
+ * Flags the instance has been destroyed.
223
+ */
224
+ __publicField(this, "destroyed", false);
225
+ this.settings = settings;
226
+ this.tag = `ExpressionManager(${settings.name})`;
227
+ }
228
+ /**
229
+ * Should be called in the constructor of derived class.
230
+ */
231
+ init() {
232
+ this.defaultExpression = this.createDefaultExpression();
233
+ this.currentExpression = this.defaultExpression;
234
+ this.stopAllExpressions();
235
+ }
236
+ /**
237
+ * Creates the default expression instance used for resets.
238
+ */
239
+ createDefaultExpression() {
240
+ return this.createExpression({}, void 0);
241
+ }
242
+ /**
243
+ * Loads an Expression. Errors in this method will not be thrown,
244
+ * but be emitted with an "expressionLoadError" event.
245
+ * @param index - Index of the expression in definitions.
246
+ * @return Promise that resolves with the Expression, or with undefined if it can't be loaded.
247
+ * @emits {@link ExpressionManagerEvents.expressionLoaded}
248
+ * @emits {@link ExpressionManagerEvents.expressionLoadError}
249
+ */
250
+ loadExpression(index) {
251
+ return __async(this, null, function* () {
252
+ if (!this.definitions[index]) {
253
+ logger.warn(this.tag, `Undefined expression at [${index}]`);
254
+ return void 0;
255
+ }
256
+ if (this.expressions[index] === null) {
257
+ logger.warn(
258
+ this.tag,
259
+ `Cannot set expression at [${index}] because it's already failed in loading.`
260
+ );
261
+ return void 0;
262
+ }
263
+ if (this.expressions[index]) {
264
+ return this.expressions[index];
265
+ }
266
+ const expression = yield this._loadExpression(index);
267
+ this.expressions[index] = expression;
268
+ return expression;
269
+ });
270
+ }
271
+ /**
272
+ * Loads the Expression. Will be implemented by Live2DFactory in order to avoid circular dependency.
273
+ * @ignore
274
+ */
275
+ _loadExpression(_index) {
276
+ throw new Error("Not implemented.");
277
+ }
278
+ /**
279
+ * Sets a random Expression that differs from current one.
280
+ * @return Promise that resolves with true if succeeded, with false otherwise.
281
+ */
282
+ setRandomExpression() {
283
+ return __async(this, null, function* () {
284
+ if (this.definitions.length) {
285
+ const availableIndices = [];
286
+ for (let i = 0; i < this.definitions.length; i++) {
287
+ if (this.expressions[i] !== null && this.expressions[i] !== this.currentExpression && i !== this.reserveExpressionIndex) {
288
+ availableIndices.push(i);
289
+ }
290
+ }
291
+ if (availableIndices.length) {
292
+ const index = Math.floor(Math.random() * availableIndices.length);
293
+ return this.setExpression(index);
294
+ }
295
+ }
296
+ return false;
297
+ });
298
+ }
299
+ /**
300
+ * Resets model's expression using {@link ExpressionManager#defaultExpression}.
301
+ */
302
+ resetExpression() {
303
+ this._setExpression(this.defaultExpression);
304
+ }
305
+ /**
306
+ * Restores model's expression to {@link currentExpression}.
307
+ */
308
+ restoreExpression() {
309
+ this._setExpression(this.currentExpression);
310
+ }
311
+ /**
312
+ * Sets an Expression.
313
+ * @param index - Either the index, or the name of the expression.
314
+ * @return Promise that resolves with true if succeeded, with false otherwise.
315
+ */
316
+ setExpression(index) {
317
+ return __async(this, null, function* () {
318
+ if (typeof index !== "number") {
319
+ index = this.getExpressionIndex(index);
320
+ }
321
+ if (!(index > -1 && index < this.definitions.length)) {
322
+ return false;
323
+ }
324
+ if (index === this.expressions.indexOf(this.currentExpression)) {
325
+ return false;
326
+ }
327
+ this.reserveExpressionIndex = index;
328
+ const expression = yield this.loadExpression(index);
329
+ if (!expression || this.reserveExpressionIndex !== index) {
330
+ return false;
331
+ }
332
+ this.reserveExpressionIndex = -1;
333
+ this.currentExpression = expression;
334
+ this._setExpression(expression);
335
+ return true;
336
+ });
337
+ }
338
+ /**
339
+ * Updates parameters of the core model.
340
+ * @return True if the parameters are actually updated.
341
+ */
342
+ update(model, now) {
343
+ if (!this.isFinished()) {
344
+ return this.updateParameters(model, now);
345
+ }
346
+ return false;
347
+ }
348
+ /**
349
+ * Destroys the instance.
350
+ * @emits {@link ExpressionManagerEvents.destroy}
351
+ */
352
+ destroy() {
353
+ this.destroyed = true;
354
+ this.emit("destroy");
355
+ const self = this;
356
+ self.definitions = void 0;
357
+ self.expressions = void 0;
358
+ }
359
+ }
360
+ const EPSILON = 0.01;
361
+ const MAX_SPEED = 40 / 7.5;
362
+ const ACCELERATION_TIME = 1 / (0.15 * 1e3);
363
+ class FocusController {
364
+ constructor() {
365
+ /** The focus position. */
366
+ __publicField(this, "targetX", 0);
367
+ /** The focus position. */
368
+ __publicField(this, "targetY", 0);
369
+ /** Current position. */
370
+ __publicField(this, "x", 0);
371
+ /** Current position. */
372
+ __publicField(this, "y", 0);
373
+ /** Current velocity. */
374
+ __publicField(this, "vx", 0);
375
+ /** Current velocity. */
376
+ __publicField(this, "vy", 0);
377
+ }
378
+ /**
379
+ * Sets the focus position.
380
+ * @param x - X position in range `[-1, 1]`.
381
+ * @param y - Y position in range `[-1, 1]`.
382
+ * @param instant - Should the focus position be instantly applied.
383
+ */
384
+ focus(x, y, instant = false) {
385
+ this.targetX = clamp(x, -1, 1);
386
+ this.targetY = clamp(y, -1, 1);
387
+ if (instant) {
388
+ this.x = this.targetX;
389
+ this.y = this.targetY;
390
+ }
391
+ }
392
+ /**
393
+ * Updates the interpolation.
394
+ * @param dt - Delta time in milliseconds.
395
+ */
396
+ update(dt) {
397
+ const dx = this.targetX - this.x;
398
+ const dy = this.targetY - this.y;
399
+ if (Math.abs(dx) < EPSILON && Math.abs(dy) < EPSILON) return;
400
+ const d = Math.sqrt(__pow(dx, 2) + __pow(dy, 2));
401
+ const maxSpeed = MAX_SPEED / (1e3 / dt);
402
+ let ax = maxSpeed * (dx / d) - this.vx;
403
+ let ay = maxSpeed * (dy / d) - this.vy;
404
+ const a = Math.sqrt(__pow(ax, 2) + __pow(ay, 2));
405
+ const maxA = maxSpeed * ACCELERATION_TIME * dt;
406
+ if (a > maxA) {
407
+ ax *= maxA / a;
408
+ ay *= maxA / a;
409
+ }
410
+ this.vx += ax;
411
+ this.vy += ay;
412
+ const v = Math.sqrt(__pow(this.vx, 2) + __pow(this.vy, 2));
413
+ const maxV = 0.5 * (Math.sqrt(__pow(maxA, 2) + 8 * maxA * d) - maxA);
414
+ if (v > maxV) {
415
+ this.vx *= maxV / v;
416
+ this.vy *= maxV / v;
417
+ }
418
+ this.x += this.vx;
419
+ this.y += this.vy;
420
+ }
421
+ }
422
+ class ModelSettings {
423
+ /**
424
+ * @param json - The settings JSON object.
425
+ * @param json.url - The `url` field must be defined to specify the settings file's URL.
426
+ */
427
+ constructor(json) {
428
+ __publicField(this, "json");
429
+ /**
430
+ * The model's name, typically used for displaying or logging. By default it's inferred from
431
+ * the URL by taking the folder name (the second to last component). In Cubism 2 it'll be overwritten
432
+ * by the `name` field of settings JSON.
433
+ */
434
+ __publicField(this, "name");
435
+ /**
436
+ * URL of the model settings file, used to resolve paths of the resource files defined in settings.
437
+ * This typically ends with `.model.json` in Cubism 2 and `.model3.json` in Cubism 4.
438
+ */
439
+ __publicField(this, "url");
440
+ /**
441
+ * Relative path of the pose file.
442
+ */
443
+ __publicField(this, "pose");
444
+ /**
445
+ * Relative path of the physics file.
446
+ */
447
+ __publicField(this, "physics");
448
+ this.json = json;
449
+ this.url = json.url;
450
+ this.name = folderName(this.url);
451
+ }
452
+ /**
453
+ * Ensures the model name is meaningful; falls back to the folder name when missing or placeholder.
454
+ */
455
+ normalizeName() {
456
+ if (!this.name || this.name.toLowerCase() === "name") {
457
+ this.name = folderName(this.url);
458
+ }
459
+ }
460
+ /**
461
+ * Picks the first non-empty, non-placeholder name from candidates and applies it.
462
+ * Falls back to {@link normalizeName} when no candidate is usable.
463
+ */
464
+ setModelName(...candidates) {
465
+ for (const candidate of candidates) {
466
+ const name = typeof candidate === "string" ? candidate.trim() : "";
467
+ if (name && name.toLowerCase() !== "name") {
468
+ this.name = name;
469
+ return;
470
+ }
471
+ }
472
+ this.normalizeName();
473
+ }
474
+ /**
475
+ * Returns the file name without extension from a path.
476
+ */
477
+ getFileStem(path) {
478
+ if (!path) return void 0;
479
+ const fileName = path.split(/[/\\]/).filter(Boolean).pop();
480
+ return fileName == null ? void 0 : fileName.replace(/\.[^.]+$/, "");
481
+ }
482
+ /**
483
+ * Resolves a relative path using the {@link url}. This is used to resolve the resource files
484
+ * defined in the settings.
485
+ * @param path - Relative path.
486
+ * @return Resolved path.
487
+ */
488
+ resolveURL(path) {
489
+ return resolveURL(this.url, path);
490
+ }
491
+ /**
492
+ * Replaces the resource files by running each file through the `replacer`.
493
+ * @param replacer - Invoked with two arguments: `(file, path)`, where `file` is the file definition,
494
+ * and `path` is its property path in the ModelSettings instance. A string must be returned to be the replacement.
495
+ *
496
+ * ```js
497
+ * modelSettings.replaceFiles((file, path) => {
498
+ * // file = "foo.moc", path = "moc"
499
+ * // file = "foo.png", path = "textures[0]"
500
+ * // file = "foo.mtn", path = "motions.idle[0].file"
501
+ * // file = "foo.motion3.json", path = "motions.idle[0].File"
502
+ *
503
+ * return "bar/" + file;
504
+ * });
505
+ * ```
506
+ */
507
+ replaceFiles(replacer) {
508
+ this.moc = replacer(this.moc, "moc");
509
+ if (this.pose !== void 0) {
510
+ this.pose = replacer(this.pose, "pose");
511
+ }
512
+ if (this.physics !== void 0) {
513
+ this.physics = replacer(this.physics, "physics");
514
+ }
515
+ for (let i = 0; i < this.textures.length; i++) {
516
+ this.textures[i] = replacer(this.textures[i], `textures[${i}]`);
517
+ }
518
+ }
519
+ /**
520
+ * Retrieves all resource files defined in the settings.
521
+ * @return A flat array of the paths of all resource files.
522
+ *
523
+ * ```js
524
+ * modelSettings.getDefinedFiles();
525
+ * // returns: ["foo.moc", "foo.png", ...]
526
+ * ```
527
+ */
528
+ getDefinedFiles() {
529
+ const files = [];
530
+ this.replaceFiles((file) => {
531
+ files.push(file);
532
+ return file;
533
+ });
534
+ return files;
535
+ }
536
+ /**
537
+ * Validates that the files defined in the settings exist in given files. Each file will be
538
+ * resolved by {@link resolveURL} before comparison.
539
+ * @param files - A flat array of file paths.
540
+ * @return All the files which are defined in the settings and also exist in given files,
541
+ * *including the optional files*.
542
+ * @throws Error if any *essential* file is defined in settings but not included in given files.
543
+ */
544
+ validateFiles(files) {
545
+ const assertFileExists = (expectedFile, shouldThrow) => {
546
+ const actualPath = this.resolveURL(expectedFile);
547
+ if (!files.includes(actualPath)) {
548
+ if (shouldThrow) {
549
+ throw new Error(
550
+ `File "${expectedFile}" is defined in settings, but doesn't exist in given files`
551
+ );
552
+ }
553
+ return false;
554
+ }
555
+ return true;
556
+ };
557
+ const essentialFiles = [this.moc, ...this.textures];
558
+ essentialFiles.forEach((texture) => assertFileExists(texture, true));
559
+ const definedFiles = this.getDefinedFiles();
560
+ return definedFiles.filter((file) => assertFileExists(file, false));
561
+ }
562
+ }
563
+ var MotionPriority = /* @__PURE__ */ ((MotionPriority2) => {
564
+ MotionPriority2[MotionPriority2["NONE"] = 0] = "NONE";
565
+ MotionPriority2[MotionPriority2["IDLE"] = 1] = "IDLE";
566
+ MotionPriority2[MotionPriority2["NORMAL"] = 2] = "NORMAL";
567
+ MotionPriority2[MotionPriority2["FORCE"] = 3] = "FORCE";
568
+ return MotionPriority2;
569
+ })(MotionPriority || {});
570
+ class MotionState {
571
+ constructor() {
572
+ /**
573
+ * Tag for logging.
574
+ */
575
+ __publicField(this, "tag");
576
+ /**
577
+ * When enabled, the states will be dumped to the logger when an exception occurs.
578
+ */
579
+ __publicField(this, "debug", false);
580
+ /**
581
+ * Priority of the current motion. Will be `MotionPriority.NONE` if there's no playing motion.
582
+ */
583
+ __publicField(this, "currentPriority", 0);
584
+ /**
585
+ * Priority of the reserved motion, which is still in loading and will be played once loaded.
586
+ * Will be `MotionPriority.NONE` if there's no reserved motion.
587
+ */
588
+ __publicField(this, "reservePriority", 0);
589
+ /**
590
+ * Group of current motion.
591
+ */
592
+ __publicField(this, "currentGroup");
593
+ /**
594
+ * Index of current motion in its group.
595
+ */
596
+ __publicField(this, "currentIndex");
597
+ /**
598
+ * Group of the reserved motion.
599
+ */
600
+ __publicField(this, "reservedGroup");
601
+ /**
602
+ * Index of the reserved motion in its group.
603
+ */
604
+ __publicField(this, "reservedIndex");
605
+ /**
606
+ * Group of the reserved idle motion.
607
+ */
608
+ __publicField(this, "reservedIdleGroup");
609
+ /**
610
+ * Index of the reserved idle motion in its group.
611
+ */
612
+ __publicField(this, "reservedIdleIndex");
613
+ }
614
+ /**
615
+ * Reserves the playback for a motion.
616
+ * @param group - The motion group.
617
+ * @param index - Index in the motion group.
618
+ * @param priority - The priority to be applied.
619
+ * @return True if the reserving has succeeded.
620
+ */
621
+ reserve(group, index, priority) {
622
+ if (priority <= 0) {
623
+ logger.log(this.tag, `Cannot start a motion with MotionPriority.NONE.`);
624
+ return false;
625
+ }
626
+ if (group === this.currentGroup && index === this.currentIndex) {
627
+ logger.log(this.tag, `Motion is already playing.`, this.dump(group, index));
628
+ return false;
629
+ }
630
+ if (group === this.reservedGroup && index === this.reservedIndex || group === this.reservedIdleGroup && index === this.reservedIdleIndex) {
631
+ logger.log(this.tag, `Motion is already reserved.`, this.dump(group, index));
632
+ return false;
633
+ }
634
+ if (priority === 1) {
635
+ if (this.currentPriority !== 0) {
636
+ logger.log(
637
+ this.tag,
638
+ `Cannot start idle motion because another motion is playing.`,
639
+ this.dump(group, index)
640
+ );
641
+ return false;
642
+ }
643
+ if (this.reservedIdleGroup !== void 0) {
644
+ logger.log(
645
+ this.tag,
646
+ `Cannot start idle motion because another idle motion has reserved.`,
647
+ this.dump(group, index)
648
+ );
649
+ return false;
650
+ }
651
+ this.setReservedIdle(group, index);
652
+ } else {
653
+ if (priority < 3) {
654
+ if (priority <= this.currentPriority) {
655
+ logger.log(
656
+ this.tag,
657
+ "Cannot start motion because another motion is playing as an equivalent or higher priority.",
658
+ this.dump(group, index)
659
+ );
660
+ return false;
661
+ }
662
+ if (priority <= this.reservePriority) {
663
+ logger.log(
664
+ this.tag,
665
+ "Cannot start motion because another motion has reserved as an equivalent or higher priority.",
666
+ this.dump(group, index)
667
+ );
668
+ return false;
669
+ }
670
+ }
671
+ this.setReserved(group, index, priority);
672
+ }
673
+ return true;
674
+ }
675
+ /**
676
+ * Requests the playback for a motion.
677
+ * @param motion - The Motion, can be undefined.
678
+ * @param group - The motion group.
679
+ * @param index - Index in the motion group.
680
+ * @param priority - The priority to be applied.
681
+ * @return True if the request has been approved, i.e. the motion is allowed to play.
682
+ */
683
+ start(motion, group, index, priority) {
684
+ if (priority === 1) {
685
+ this.setReservedIdle(void 0, void 0);
686
+ if (this.currentPriority !== 0) {
687
+ logger.log(
688
+ this.tag,
689
+ "Cannot start idle motion because another motion is playing.",
690
+ this.dump(group, index)
691
+ );
692
+ return false;
693
+ }
694
+ } else {
695
+ if (group !== this.reservedGroup || index !== this.reservedIndex) {
696
+ logger.log(
697
+ this.tag,
698
+ "Cannot start motion because another motion has taken the place.",
699
+ this.dump(group, index)
700
+ );
701
+ return false;
702
+ }
703
+ this.setReserved(
704
+ void 0,
705
+ void 0,
706
+ 0
707
+ /* NONE */
708
+ );
709
+ }
710
+ if (!motion) {
711
+ return false;
712
+ }
713
+ this.setCurrent(group, index, priority);
714
+ return true;
715
+ }
716
+ /**
717
+ * Notifies the motion playback has finished.
718
+ */
719
+ complete() {
720
+ this.setCurrent(
721
+ void 0,
722
+ void 0,
723
+ 0
724
+ /* NONE */
725
+ );
726
+ }
727
+ /**
728
+ * Sets the current motion.
729
+ */
730
+ setCurrent(group, index, priority) {
731
+ this.currentPriority = priority;
732
+ this.currentGroup = group;
733
+ this.currentIndex = index;
734
+ }
735
+ /**
736
+ * Sets the reserved motion.
737
+ */
738
+ setReserved(group, index, priority) {
739
+ this.reservePriority = priority;
740
+ this.reservedGroup = group;
741
+ this.reservedIndex = index;
742
+ }
743
+ /**
744
+ * Sets the reserved idle motion.
745
+ */
746
+ setReservedIdle(group, index) {
747
+ this.reservedIdleGroup = group;
748
+ this.reservedIdleIndex = index;
749
+ }
750
+ /**
751
+ * Checks if a Motion is currently playing or has reserved.
752
+ * @return True if active.
753
+ */
754
+ isActive(group, index) {
755
+ return group === this.currentGroup && index === this.currentIndex || group === this.reservedGroup && index === this.reservedIndex || group === this.reservedIdleGroup && index === this.reservedIdleIndex;
756
+ }
757
+ /**
758
+ * Resets the state.
759
+ */
760
+ reset() {
761
+ this.setCurrent(
762
+ void 0,
763
+ void 0,
764
+ 0
765
+ /* NONE */
766
+ );
767
+ this.setReserved(
768
+ void 0,
769
+ void 0,
770
+ 0
771
+ /* NONE */
772
+ );
773
+ this.setReservedIdle(void 0, void 0);
774
+ }
775
+ /**
776
+ * Checks if an idle motion should be requests to play.
777
+ */
778
+ shouldRequestIdleMotion() {
779
+ return this.currentGroup === void 0 && this.reservedIdleGroup === void 0;
780
+ }
781
+ /**
782
+ * Checks if the model's expression should be overridden by the motion.
783
+ */
784
+ shouldOverrideExpression() {
785
+ return !config.preserveExpressionOnMotion && this.currentPriority > 1;
786
+ }
787
+ /**
788
+ * Dumps the state for debugging.
789
+ */
790
+ dump(requestedGroup, requestedIndex) {
791
+ if (this.debug) {
792
+ const keys = [
793
+ "currentPriority",
794
+ "reservePriority",
795
+ "currentGroup",
796
+ "currentIndex",
797
+ "reservedGroup",
798
+ "reservedIndex",
799
+ "reservedIdleGroup",
800
+ "reservedIdleIndex"
801
+ ];
802
+ return `
803
+ <Requested> group = "${requestedGroup}", index = ${requestedIndex}
804
+ ` + keys.map((key) => "[" + key + "] " + this[key]).join("\n");
805
+ }
806
+ return "";
807
+ }
808
+ }
809
+ const TAG$2 = "SoundManager";
810
+ const VOLUME = 0.5;
811
+ sound.disableAutoPause = true;
812
+ class SoundManager {
813
+ /**
814
+ * Global volume that applies to all the sounds.
815
+ */
816
+ static get volume() {
817
+ return this._volume;
818
+ }
819
+ static set volume(value) {
820
+ this._volume = (value > 1 ? 1 : value < 0 ? 0 : value) || 0;
821
+ this.audios.forEach((audio) => audio.volume = this._volume);
822
+ }
823
+ // TODO: return an ID?
824
+ /**
825
+ * Creates an audio element and adds it to the {@link audios}.
826
+ * @param file - URL of the sound file.
827
+ * @param onError - Callback invoked when error occurs.
828
+ * @return Created audio element.
829
+ */
830
+ static add(file, onError) {
831
+ return __async(this, null, function* () {
832
+ try {
833
+ const task = new Promise((resolve, reject) => {
834
+ const audio = Sound.from({
835
+ url: file,
836
+ volume: this._volume,
837
+ preload: true,
838
+ loaded: () => {
839
+ if (!(audio.media instanceof webaudio.WebAudioMedia)) {
840
+ reject(new Error(`Error: ${file} is not WebAudioMedia`));
841
+ }
842
+ resolve(audio);
843
+ }
844
+ });
845
+ });
846
+ return yield task;
847
+ } catch (e) {
848
+ logger.warn(TAG$2, `Error occurred on "${file}"`, e);
849
+ onError == null ? void 0 : onError(e);
850
+ return null;
851
+ }
852
+ });
853
+ }
854
+ /**
855
+ * Plays the sound.
856
+ * @param audio - An audio element.
857
+ * @param onFinish - Callback invoked when the playback has finished.
858
+ */
859
+ static play(audio, onFinish) {
860
+ void audio.play({
861
+ singleInstance: true,
862
+ complete: () => {
863
+ onFinish == null ? void 0 : onFinish();
864
+ audio.destroy();
865
+ }
866
+ });
867
+ }
868
+ static addAnalyzer(audio, context) {
869
+ const media = audio.media;
870
+ const source = context.createBufferSource();
871
+ source.buffer = media.buffer;
872
+ const analyser = context.createAnalyser();
873
+ analyser.fftSize = config.fftSize;
874
+ analyser.minDecibels = -90;
875
+ analyser.maxDecibels = -10;
876
+ analyser.smoothingTimeConstant = 0.85;
877
+ source.connect(analyser);
878
+ source.start(0);
879
+ this.analysers.push(analyser);
880
+ return analyser;
881
+ }
882
+ /**
883
+ * Get volume for lip sync
884
+ * @param analyser - An analyzer element.
885
+ * @return Returns value to feed into lip sync
886
+ */
887
+ static analyze(analyser) {
888
+ if (!analyser) return parseFloat(Math.random().toFixed(1));
889
+ const buffer = new Float32Array(analyser.fftSize);
890
+ analyser.getFloatTimeDomainData(buffer);
891
+ let sumSquares = 0;
892
+ for (let i = 0; i < buffer.length; i++) {
893
+ sumSquares += __pow(buffer[i], 2);
894
+ }
895
+ const rms = Math.sqrt(sumSquares / buffer.length);
896
+ const minDecibel = -100;
897
+ const db = 20 * Math.log10(rms || __pow(10, minDecibel / 20));
898
+ const scaledDb = Math.min(
899
+ Math.max((db - analyser.minDecibels) / (analyser.maxDecibels - analyser.minDecibels), 0),
900
+ 1
901
+ );
902
+ return parseFloat(scaledDb.toFixed(1));
903
+ }
904
+ /**
905
+ * Disposes an audio element and removes it from {@link audios}.
906
+ * @param audio - An audio element.
907
+ */
908
+ static dispose(audio) {
909
+ audio.pause();
910
+ remove(this.audios, audio);
911
+ }
912
+ /**
913
+ * Destroys all managed audios.
914
+ */
915
+ static destroy() {
916
+ for (let i = this.contexts.length - 1; i >= 0; i--) {
917
+ const context = this.contexts[i];
918
+ void (context == null ? void 0 : context.close().catch((e) => {
919
+ logger.warn(TAG$2, "Failed to close AudioContext.", e);
920
+ }));
921
+ }
922
+ for (let i = this.audios.length - 1; i >= 0; i--) {
923
+ this.dispose(this.audios[i]);
924
+ }
925
+ }
926
+ }
927
+ /**
928
+ * Audio elements playing or pending to play. Finished audios will be removed automatically.
929
+ */
930
+ __publicField(SoundManager, "audios", []);
931
+ __publicField(SoundManager, "analysers", []);
932
+ __publicField(SoundManager, "contexts", []);
933
+ __publicField(SoundManager, "_volume", VOLUME);
934
+ var MotionPreloadStrategy = /* @__PURE__ */ ((MotionPreloadStrategy2) => {
935
+ MotionPreloadStrategy2["ALL"] = "ALL";
936
+ MotionPreloadStrategy2["IDLE"] = "IDLE";
937
+ MotionPreloadStrategy2["NONE"] = "NONE";
938
+ return MotionPreloadStrategy2;
939
+ })(MotionPreloadStrategy || {});
940
+ class MotionManager extends EventEmitter {
941
+ /**
942
+ * Constructor for MotionManager.
943
+ * @param parent - The parent InternalModel.
944
+ */
945
+ constructor(parent) {
946
+ super();
947
+ /**
948
+ * Tag for logging.
949
+ * @type {string}
950
+ */
951
+ __publicField(this, "tag");
952
+ /**
953
+ * The ModelSettings reference.
954
+ * @type {ModelSettings}
955
+ */
956
+ __publicField(this, "settings");
957
+ /**
958
+ * The Motions. The structure is the same as {@link definitions}, initially each group contains
959
+ * an empty array, which means all motions will be `undefined`. When a Motion has been loaded,
960
+ * it'll fill the place in which it should be; when it fails to load, the place will be filled
961
+ * with `null`.
962
+ * @type {Partial<Record<string, (Motion | undefined | null)[]>>}
963
+ */
964
+ __publicField(this, "motionGroups", {});
965
+ /**
966
+ * Maintains the state of this MotionManager.
967
+ * @type {MotionState}
968
+ */
969
+ __publicField(this, "state", new MotionState());
970
+ /**
971
+ * Audio element of the current motion if a sound file is defined with it.
972
+ * @type {Sound | undefined}
973
+ */
974
+ __publicField(this, "currentAudio");
975
+ /**
976
+ * Analyzer element for the current sound being played.
977
+ * @type {AnalyserNode | undefined}
978
+ */
979
+ __publicField(this, "currentAnalyzer");
980
+ /**
981
+ * Context element for the current sound being played.
982
+ * @type {AudioContext | undefined}
983
+ */
984
+ __publicField(this, "currentContext");
985
+ /**
986
+ * Flags whether there is a motion currently playing.
987
+ * @type {boolean}
988
+ */
989
+ __publicField(this, "playing", false);
990
+ /**
991
+ * Flags whether the instance has been destroyed.
992
+ * @type {boolean}
993
+ */
994
+ __publicField(this, "destroyed", false);
995
+ /**
996
+ * Reference to the parent InternalModel.
997
+ * @type {InternalModel}
998
+ */
999
+ __publicField(this, "parent");
1000
+ this.settings = parent.settings;
1001
+ this.tag = `MotionManager(${this.settings.name})`;
1002
+ this.state.tag = this.tag;
1003
+ this.parent = parent;
1004
+ }
1005
+ /**
1006
+ * Should be called in the constructor of derived class to initialize options and setup motions.
1007
+ * @param options - Initialization options for the manager.
1008
+ */
1009
+ init(options) {
1010
+ if (options == null ? void 0 : options.idleMotionGroup) {
1011
+ this.groups.idle = options.idleMotionGroup;
1012
+ }
1013
+ this.setupMotions(options);
1014
+ this.stopAllMotions();
1015
+ }
1016
+ /**
1017
+ * Sets up motions from the definitions, and preloads them according to the preload strategy.
1018
+ * @param options - Options controlling which motions to preload.
1019
+ */
1020
+ setupMotions(options) {
1021
+ if (!this.definitions) {
1022
+ logger.warn(this.tag, "Motion definitions are not initialized.");
1023
+ return;
1024
+ }
1025
+ for (const group of Object.keys(this.definitions)) {
1026
+ this.motionGroups[group] = [];
1027
+ }
1028
+ let groups;
1029
+ switch (options == null ? void 0 : options.motionPreload) {
1030
+ case "NONE":
1031
+ return;
1032
+ case "ALL":
1033
+ groups = Object.keys(this.definitions);
1034
+ break;
1035
+ case "IDLE":
1036
+ default:
1037
+ groups = [this.groups.idle];
1038
+ break;
1039
+ }
1040
+ for (const group of groups) {
1041
+ const definitions = this.definitions[group];
1042
+ if (definitions) {
1043
+ for (let i = 0; i < definitions.length; i++) {
1044
+ void this.loadMotion(group, i);
1045
+ }
1046
+ }
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Loads a Motion in a motion group. Errors in this method will not be thrown,
1051
+ * but be emitted with a "motionLoadError" event.
1052
+ * @param group - The motion group.
1053
+ * @param index - Index in the motion group.
1054
+ * @return Promise that resolves with the Motion, or with undefined if it can't be loaded.
1055
+ * @emits {@link MotionManagerEvents.motionLoaded}
1056
+ * @emits {@link MotionManagerEvents.motionLoadError}
1057
+ */
1058
+ loadMotion(group, index) {
1059
+ return __async(this, null, function* () {
1060
+ var _a, _b;
1061
+ if (this.destroyed) {
1062
+ return void 0;
1063
+ }
1064
+ const definition = this.getMotionDefinition(group, index);
1065
+ if (!definition) {
1066
+ return void 0;
1067
+ }
1068
+ const groupMotions = (_b = (_a = this.motionGroups)[group]) != null ? _b : _a[group] = [];
1069
+ if (groupMotions[index] === null) {
1070
+ logger.warn(
1071
+ this.tag,
1072
+ `Cannot start motion at "${group}"[${index}] because it's already failed in loading.`
1073
+ );
1074
+ return void 0;
1075
+ }
1076
+ if (groupMotions[index]) {
1077
+ return groupMotions[index];
1078
+ }
1079
+ const motion = yield this._loadMotion(group, index);
1080
+ if (this.destroyed) {
1081
+ return;
1082
+ }
1083
+ groupMotions[index] = motion != null ? motion : null;
1084
+ return motion;
1085
+ });
1086
+ }
1087
+ /**
1088
+ * Loads the Motion. Will be implemented by Live2DFactory in order to avoid circular dependency.
1089
+ * @ignore
1090
+ */
1091
+ _loadMotion(_group, _index) {
1092
+ throw new Error("Not implemented.");
1093
+ }
1094
+ /**
1095
+ * Initializes audio playback and sets up audio analysis for lipsync.
1096
+ * @param audio - The Sound to initialize.
1097
+ * @param volume - The playback volume (0-1).
1098
+ */
1099
+ initializeAudio(audio, volume) {
1100
+ this.currentAudio = audio;
1101
+ SoundManager.volume = volume;
1102
+ this.currentContext = audio.context.audioContext;
1103
+ this.currentAnalyzer = SoundManager.addAnalyzer(this.currentAudio, this.currentContext);
1104
+ }
1105
+ /**
1106
+ * Only play sound with lip sync.
1107
+ * @param sound - The audio url or base64 content.
1108
+ * @param volume - Volume of the sound (0-1).
1109
+ * @param expression - Expression to apply while playing sound.
1110
+ * @param resetExpression - Whether to reset the expression before and after playing sound (default: true).
1111
+ * @param crossOrigin - Cross origin setting.
1112
+ * @param onFinish - Callback when playback finishes.
1113
+ * @param onError - Callback when playback errors.
1114
+ * @returns Promise that resolves with true if the sound is playing, false otherwise.
1115
+ */
1116
+ speak(_0) {
1117
+ return __async(this, arguments, function* (sound2, {
1118
+ volume = VOLUME,
1119
+ expression,
1120
+ resetExpression = true,
1121
+ onFinish,
1122
+ onError
1123
+ } = {}) {
1124
+ if (!config.sound) {
1125
+ return false;
1126
+ }
1127
+ let audio;
1128
+ if (this.currentAudio) {
1129
+ if (this.currentAudio.isPlaying) {
1130
+ return false;
1131
+ }
1132
+ }
1133
+ let soundURL;
1134
+ const isBase64Content = sound2 && sound2.startsWith("data:");
1135
+ if (sound2 && !isBase64Content) {
1136
+ const A = document.createElement("a");
1137
+ A.href = sound2;
1138
+ sound2 = A.href;
1139
+ soundURL = sound2;
1140
+ } else {
1141
+ soundURL = "data:audio/";
1142
+ }
1143
+ const file = sound2;
1144
+ if (file) {
1145
+ try {
1146
+ audio = yield SoundManager.add(file, (e, that = this) => {
1147
+ logger.error(this.tag, "Error during audio playback:", e);
1148
+ onError == null ? void 0 : onError(e);
1149
+ if (resetExpression && expression && that.expressionManager) {
1150
+ that.expressionManager.resetExpression();
1151
+ }
1152
+ that.currentAudio = void 0;
1153
+ });
1154
+ this.initializeAudio(audio, volume);
1155
+ } catch (e) {
1156
+ logger.warn(this.tag, "Failed to create audio", soundURL, e);
1157
+ return false;
1158
+ }
1159
+ }
1160
+ if (audio) {
1161
+ let playSuccess = true;
1162
+ try {
1163
+ if (config.motionSync) {
1164
+ SoundManager.play(audio, () => {
1165
+ onFinish == null ? void 0 : onFinish();
1166
+ if (resetExpression && expression && this.expressionManager) {
1167
+ this.expressionManager.resetExpression();
1168
+ }
1169
+ this.currentAudio = void 0;
1170
+ });
1171
+ }
1172
+ } catch (e) {
1173
+ logger.warn(this.tag, "Failed to play audio", audio.url, e);
1174
+ playSuccess = false;
1175
+ }
1176
+ if (!playSuccess) {
1177
+ return false;
1178
+ }
1179
+ }
1180
+ if (this.state.shouldOverrideExpression()) {
1181
+ if (this.expressionManager) this.expressionManager.resetExpression();
1182
+ }
1183
+ if (expression && this.expressionManager) {
1184
+ yield this.expressionManager.setExpression(expression);
1185
+ }
1186
+ this.playing = true;
1187
+ return true;
1188
+ });
1189
+ }
1190
+ /**
1191
+ * Starts a motion with the given priority.
1192
+ * @param group - The motion group.
1193
+ * @param index - Index in the motion group.
1194
+ * @param priority - The priority to be applied. Default: NORMAL (2).
1195
+ * @param sound - The audio url or base64 content.
1196
+ * @param volume - Volume of the sound (0-1).
1197
+ * @param expression - Expression to apply while playing sound.
1198
+ * @param resetExpression - Whether to reset the expression before and after playing sound (default: true).
1199
+ * @param crossOrigin - Cross origin setting.
1200
+ * @param onFinish - Callback when playback finishes.
1201
+ * @param onError - Callback when playback errors.
1202
+ * @param ignoreParamIds - The ids to be ignored.
1203
+ * @return Promise that resolves with true if the motion is successfully started, false otherwise.
1204
+ */
1205
+ startMotion(_0, _1) {
1206
+ return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, {
1207
+ sound: sound2 = void 0,
1208
+ volume = VOLUME,
1209
+ expression = void 0,
1210
+ resetExpression = true,
1211
+ onFinish,
1212
+ onError,
1213
+ ignoreParamIds = []
1214
+ } = {}) {
1215
+ if (this.destroyed) {
1216
+ return false;
1217
+ }
1218
+ if (!this.state.reserve(group, index, priority)) {
1219
+ return false;
1220
+ }
1221
+ if (this.currentAudio) {
1222
+ if (this.currentAudio.isPlaying && priority != MotionPriority.FORCE) {
1223
+ return false;
1224
+ }
1225
+ }
1226
+ const definition = this.getMotionDefinition(group, index);
1227
+ if (!definition) {
1228
+ return false;
1229
+ }
1230
+ if (this.currentAudio) {
1231
+ SoundManager.dispose(this.currentAudio);
1232
+ }
1233
+ let audio;
1234
+ let soundURL;
1235
+ const isBase64Content = sound2 && sound2.startsWith("data:");
1236
+ if (sound2 && !isBase64Content) {
1237
+ const A = document.createElement("a");
1238
+ A.href = sound2;
1239
+ sound2 = A.href;
1240
+ soundURL = sound2;
1241
+ } else {
1242
+ soundURL = this.getSoundFile(definition);
1243
+ if (soundURL) {
1244
+ soundURL = this.settings.resolveURL(soundURL);
1245
+ }
1246
+ }
1247
+ const file = soundURL;
1248
+ if (file) {
1249
+ try {
1250
+ audio = yield SoundManager.add(file, (e, that = this) => {
1251
+ logger.error(this.tag, "Error during audio playback:", e);
1252
+ onError == null ? void 0 : onError(e);
1253
+ if (resetExpression && expression && that.expressionManager) {
1254
+ that.expressionManager.resetExpression();
1255
+ }
1256
+ that.currentAudio = void 0;
1257
+ });
1258
+ this.initializeAudio(audio, volume);
1259
+ } catch (e) {
1260
+ logger.warn(this.tag, "Failed to create audio", soundURL, e);
1261
+ }
1262
+ }
1263
+ const motion = yield this.loadMotion(group, index);
1264
+ if (audio) {
1265
+ if (config.motionSync) {
1266
+ try {
1267
+ SoundManager.play(audio, (that = this) => {
1268
+ onFinish == null ? void 0 : onFinish();
1269
+ if (resetExpression && expression && that.expressionManager) {
1270
+ that.expressionManager.resetExpression();
1271
+ }
1272
+ that.currentAudio = void 0;
1273
+ });
1274
+ } catch (e) {
1275
+ logger.warn(this.tag, "Failed to play audio", audio.url, e);
1276
+ }
1277
+ }
1278
+ }
1279
+ if (!this.state.start(motion, group, index, priority)) {
1280
+ if (audio) {
1281
+ SoundManager.dispose(audio);
1282
+ this.currentAudio = void 0;
1283
+ }
1284
+ return false;
1285
+ }
1286
+ if (this.state.shouldOverrideExpression()) {
1287
+ if (this.expressionManager) this.expressionManager.resetExpression();
1288
+ }
1289
+ logger.log(this.tag, "Start motion:", this.getMotionName(definition));
1290
+ this.emit("motionStart", group, index, audio);
1291
+ if (expression && this.expressionManager && this.state.shouldOverrideExpression()) {
1292
+ yield this.expressionManager.setExpression(expression);
1293
+ }
1294
+ this.playing = true;
1295
+ if (motion) {
1296
+ this._startMotion(motion, void 0, ignoreParamIds);
1297
+ }
1298
+ return true;
1299
+ });
1300
+ }
1301
+ /**
1302
+ * Starts a random Motion as given priority.
1303
+ * @param group - The motion group.
1304
+ * @param priority - The priority to be applied. Default: IDLE (1).
1305
+ * @param sound - The audio url or base64 content.
1306
+ * @param volume - Volume of the sound (0-1).
1307
+ * @param expression - Expression to apply while playing sound.
1308
+ * @param resetExpression - Whether to reset the expression before and after playing sound (default: true).
1309
+ * @param crossOrigin - Cross origin setting.
1310
+ * @param onFinish - Callback when playback finishes.
1311
+ * @param onError - Callback when playback errors.
1312
+ * @return Promise that resolves with true if the motion is successfully started, false otherwise.
1313
+ */
1314
+ startRandomMotion(_0, _1) {
1315
+ return __async(this, arguments, function* (group, priority, {
1316
+ sound: sound2,
1317
+ volume = VOLUME,
1318
+ expression,
1319
+ resetExpression = true,
1320
+ onFinish,
1321
+ onError
1322
+ } = {}) {
1323
+ var _a, _b;
1324
+ if (this.destroyed) {
1325
+ return false;
1326
+ }
1327
+ const groupDefs = (_a = this.definitions) == null ? void 0 : _a[group];
1328
+ if (groupDefs == null ? void 0 : groupDefs.length) {
1329
+ const availableIndices = [];
1330
+ const groupMotions = (_b = this.motionGroups[group]) != null ? _b : [];
1331
+ for (let i = 0; i < groupDefs.length; i++) {
1332
+ if (groupMotions[i] !== null && !this.state.isActive(group, i)) {
1333
+ availableIndices.push(i);
1334
+ }
1335
+ }
1336
+ if (availableIndices.length) {
1337
+ const index = availableIndices[Math.floor(Math.random() * availableIndices.length)];
1338
+ return this.startMotion(group, index, priority, {
1339
+ sound: sound2,
1340
+ volume,
1341
+ expression,
1342
+ resetExpression,
1343
+ onFinish,
1344
+ onError
1345
+ });
1346
+ }
1347
+ }
1348
+ return false;
1349
+ });
1350
+ }
1351
+ /**
1352
+ * Stops current audio playback and lipsync.
1353
+ */
1354
+ stopSpeaking() {
1355
+ if (this.currentAudio) {
1356
+ SoundManager.dispose(this.currentAudio);
1357
+ this.currentAudio = void 0;
1358
+ }
1359
+ }
1360
+ /**
1361
+ * Stops all playing motions as well as the sound.
1362
+ */
1363
+ stopAllMotions() {
1364
+ this._stopAllMotions();
1365
+ this.state.reset();
1366
+ this.stopSpeaking();
1367
+ }
1368
+ /**
1369
+ * Updates parameters of the core model.
1370
+ * @param model - The core model.
1371
+ * @param now - Current time in milliseconds.
1372
+ * @return True if the parameters have been actually updated.
1373
+ */
1374
+ update(model, now) {
1375
+ var _a;
1376
+ if (this.isFinished()) {
1377
+ if (this.playing) {
1378
+ this.playing = false;
1379
+ this.emit("motionFinish");
1380
+ }
1381
+ if (this.state.shouldOverrideExpression()) {
1382
+ (_a = this.expressionManager) == null ? void 0 : _a.restoreExpression();
1383
+ }
1384
+ this.state.complete();
1385
+ if (this.state.shouldRequestIdleMotion()) {
1386
+ void this.startRandomMotion(this.groups.idle, MotionPriority.IDLE);
1387
+ }
1388
+ }
1389
+ return this.updateParameters(model, now);
1390
+ }
1391
+ /**
1392
+ * Move the mouth for lipsync.
1393
+ * @returns The current lipsync value.
1394
+ */
1395
+ mouthSync() {
1396
+ if (this.currentAnalyzer) {
1397
+ return SoundManager.analyze(this.currentAnalyzer);
1398
+ } else {
1399
+ return 0;
1400
+ }
1401
+ }
1402
+ /**
1403
+ * Destroys the instance and releases all resources.
1404
+ * @emits {@link MotionManagerEvents.destroy}
1405
+ */
1406
+ destroy() {
1407
+ var _a;
1408
+ this.destroyed = true;
1409
+ this.emit("destroy");
1410
+ this.stopAllMotions();
1411
+ (_a = this.expressionManager) == null ? void 0 : _a.destroy();
1412
+ const self = this;
1413
+ self.definitions = void 0;
1414
+ self.motionGroups = void 0;
1415
+ }
1416
+ /**
1417
+ * Loads a motion and applies the given expression with FORCE priority.
1418
+ * @param group - The motion group.
1419
+ * @param index - The motion index.
1420
+ * @param expression - Expression to apply (optional).
1421
+ * @returns The loaded motion, or null if not started.
1422
+ * @protected
1423
+ */
1424
+ getMotionAndApplyExpression(group, index, expression) {
1425
+ return __async(this, null, function* () {
1426
+ if (this.destroyed) {
1427
+ return null;
1428
+ }
1429
+ if (!this.state.reserve(group, index, MotionPriority.FORCE)) {
1430
+ return null;
1431
+ }
1432
+ const definition = this.getMotionDefinition(group, index);
1433
+ if (!definition) {
1434
+ return null;
1435
+ }
1436
+ if (this.currentAudio) {
1437
+ SoundManager.dispose(this.currentAudio);
1438
+ }
1439
+ const motion = yield this.loadMotion(group, index);
1440
+ if (!this.state.start(motion, group, index, MotionPriority.FORCE)) {
1441
+ return null;
1442
+ }
1443
+ if (this.state.shouldOverrideExpression()) {
1444
+ if (this.expressionManager) this.expressionManager.resetExpression();
1445
+ }
1446
+ logger.log(this.tag, "Start motion:", this.getMotionName(definition));
1447
+ this.emit("motionStart", group, index, void 0);
1448
+ if (expression && this.expressionManager && this.state.shouldOverrideExpression()) {
1449
+ yield this.expressionManager.setExpression(expression);
1450
+ }
1451
+ return motion;
1452
+ });
1453
+ }
1454
+ getMotionDefinition(group, index) {
1455
+ var _a, _b;
1456
+ const definition = (_b = (_a = this.definitions) == null ? void 0 : _a[group]) == null ? void 0 : _b[index];
1457
+ if (!definition) {
1458
+ logger.warn(this.tag, `Undefined motion at "${group}"[${index}]`);
1459
+ }
1460
+ return definition;
1461
+ }
1462
+ }
1463
+ function normalizeHitAreaDefs(raw, resolveIndex) {
1464
+ if (!Array.isArray(raw)) {
1465
+ return [];
1466
+ }
1467
+ const defs = [];
1468
+ for (const hitArea of raw) {
1469
+ if (!hitArea || typeof hitArea !== "object") {
1470
+ continue;
1471
+ }
1472
+ const record = hitArea;
1473
+ const id = typeof record.id === "string" ? record.id : typeof record.Id === "string" ? record.Id : void 0;
1474
+ const name = typeof record.name === "string" ? record.name : typeof record.Name === "string" ? record.Name : void 0;
1475
+ if (!id || !name) {
1476
+ continue;
1477
+ }
1478
+ defs.push({
1479
+ id,
1480
+ name,
1481
+ index: resolveIndex(id)
1482
+ });
1483
+ }
1484
+ return defs;
1485
+ }
1486
+ const tempBounds = { x: 0, y: 0, width: 0, height: 0 };
1487
+ class InternalModel extends EventEmitter {
1488
+ constructor() {
1489
+ super(...arguments);
1490
+ __publicField(this, "focusController", new FocusController());
1491
+ __publicField(this, "pose");
1492
+ __publicField(this, "physics");
1493
+ /**
1494
+ * Original canvas width of the model. Note this doesn't represent the model's real size,
1495
+ * as the model can overflow from its canvas.
1496
+ */
1497
+ __publicField(this, "originalWidth", 0);
1498
+ /**
1499
+ * Original canvas height of the model. Note this doesn't represent the model's real size,
1500
+ * as the model can overflow from its canvas.
1501
+ */
1502
+ __publicField(this, "originalHeight", 0);
1503
+ /**
1504
+ * Canvas width of the model, scaled by the `width` of the model's layout.
1505
+ */
1506
+ __publicField(this, "width", 0);
1507
+ /**
1508
+ * Canvas height of the model, scaled by the `height` of the model's layout.
1509
+ */
1510
+ __publicField(this, "height", 0);
1511
+ /**
1512
+ * Local transformation, calculated from the model's layout.
1513
+ */
1514
+ __publicField(this, "localTransform", new Matrix());
1515
+ /**
1516
+ * The final matrix to draw the model.
1517
+ */
1518
+ __publicField(this, "drawingMatrix", new Matrix());
1519
+ // TODO: change structure
1520
+ /**
1521
+ * The hit area definitions, keyed by their names.
1522
+ */
1523
+ __publicField(this, "hitAreas", {});
1524
+ /**
1525
+ * Flags whether `gl.UNPACK_FLIP_Y_WEBGL` should be enabled when binding the textures.
1526
+ */
1527
+ __publicField(this, "textureFlipY", false);
1528
+ /**
1529
+ * WebGL viewport when drawing the model. The format is `[x, y, width, height]`.
1530
+ */
1531
+ __publicField(this, "viewport", [0, 0, 0, 0]);
1532
+ /**
1533
+ * Flags this instance has been destroyed.
1534
+ */
1535
+ __publicField(this, "destroyed", false);
1536
+ }
1537
+ /**
1538
+ * Should be called in the constructor of derived class.
1539
+ */
1540
+ init() {
1541
+ this.setupLayout();
1542
+ this.setupHitAreas();
1543
+ }
1544
+ /**
1545
+ * Sets up the model's size and local transform by the model's layout.
1546
+ */
1547
+ setupLayout() {
1548
+ const self = this;
1549
+ const size = this.getSize();
1550
+ self.originalWidth = size[0];
1551
+ self.originalHeight = size[1];
1552
+ const layout = Object.assign(
1553
+ {
1554
+ width: LOGICAL_WIDTH,
1555
+ height: LOGICAL_HEIGHT
1556
+ },
1557
+ this.getLayout()
1558
+ );
1559
+ this.localTransform.scale(layout.width / LOGICAL_WIDTH, layout.height / LOGICAL_HEIGHT);
1560
+ self.width = this.originalWidth * this.localTransform.a;
1561
+ self.height = this.originalHeight * this.localTransform.d;
1562
+ const offsetX = layout.x !== void 0 && layout.x - layout.width / 2 || layout.centerX !== void 0 && layout.centerX || layout.left !== void 0 && layout.left - layout.width / 2 || layout.right !== void 0 && layout.right + layout.width / 2 || 0;
1563
+ const offsetY = layout.y !== void 0 && layout.y - layout.height / 2 || layout.centerY !== void 0 && layout.centerY || layout.top !== void 0 && layout.top - layout.height / 2 || layout.bottom !== void 0 && layout.bottom + layout.height / 2 || 0;
1564
+ this.localTransform.translate(this.width * offsetX, -this.height * offsetY);
1565
+ }
1566
+ /**
1567
+ * Sets up the hit areas by their definitions in settings.
1568
+ */
1569
+ setupHitAreas() {
1570
+ const definitions = this.getHitAreaDefs();
1571
+ this.hitAreas = {};
1572
+ for (const def of definitions) {
1573
+ if (!def.name) {
1574
+ continue;
1575
+ }
1576
+ this.hitAreas[def.name] = def;
1577
+ }
1578
+ }
1579
+ /**
1580
+ * Hit-test on the model.
1581
+ * @param x - Position in model canvas.
1582
+ * @param y - Position in model canvas.
1583
+ * @return The names of the *hit* hit areas. Can be empty if none is hit.
1584
+ */
1585
+ hitTest(x, y) {
1586
+ return Object.keys(this.hitAreas).filter((hitAreaName) => this.isHit(hitAreaName, x, y));
1587
+ }
1588
+ /**
1589
+ * Hit-test for a single hit area.
1590
+ * @param hitAreaName - The hit area's name.
1591
+ * @param x - Position in model canvas.
1592
+ * @param y - Position in model canvas.
1593
+ * @return True if hit.
1594
+ */
1595
+ isHit(hitAreaName, x, y) {
1596
+ const hitArea = this.hitAreas[hitAreaName];
1597
+ if (!hitArea) {
1598
+ return false;
1599
+ }
1600
+ let drawIndex = hitArea.index;
1601
+ if (drawIndex < 0) {
1602
+ if (!hitArea.id) {
1603
+ return false;
1604
+ }
1605
+ drawIndex = this.getDrawableIndex(hitArea.id);
1606
+ if (drawIndex < 0) {
1607
+ return false;
1608
+ }
1609
+ hitArea.index = drawIndex;
1610
+ }
1611
+ const bounds = this.getDrawableBounds(drawIndex, tempBounds);
1612
+ return bounds.x <= x && x <= bounds.x + bounds.width && bounds.y <= y && y <= bounds.y + bounds.height;
1613
+ }
1614
+ /**
1615
+ * Gets a drawable's bounds.
1616
+ * @param index - Index of the drawable.
1617
+ * @param bounds - Object to store the output values.
1618
+ * @return The bounds in model canvas space.
1619
+ */
1620
+ getDrawableBounds(index, bounds) {
1621
+ const vertices = this.getDrawableVertices(index);
1622
+ let left = vertices[0];
1623
+ let right = vertices[0];
1624
+ let top = vertices[1];
1625
+ let bottom = vertices[1];
1626
+ for (let i = 0; i < vertices.length; i += 2) {
1627
+ const vx = vertices[i];
1628
+ const vy = vertices[i + 1];
1629
+ left = Math.min(vx, left);
1630
+ right = Math.max(vx, right);
1631
+ top = Math.min(vy, top);
1632
+ bottom = Math.max(vy, bottom);
1633
+ }
1634
+ bounds != null ? bounds : bounds = {};
1635
+ bounds.x = left;
1636
+ bounds.y = top;
1637
+ bounds.width = right - left;
1638
+ bounds.height = bottom - top;
1639
+ return bounds;
1640
+ }
1641
+ /**
1642
+ * Updates the model's transform.
1643
+ * @param transform - The world transform.
1644
+ */
1645
+ updateTransform(transform) {
1646
+ this.drawingMatrix.copyFrom(transform).append(this.localTransform);
1647
+ }
1648
+ /**
1649
+ * Updates the model's parameters.
1650
+ * @param dt - Elapsed time in milliseconds from last frame.
1651
+ * @param _now - Current time in milliseconds.
1652
+ */
1653
+ update(dt, _now) {
1654
+ this.focusController.update(dt);
1655
+ }
1656
+ /**
1657
+ * Destroys the model and all related resources.
1658
+ * @emits {@link `InternalModelEvents.destroy` | destroy}
1659
+ */
1660
+ destroy() {
1661
+ this.destroyed = true;
1662
+ this.emit("destroy");
1663
+ this.motionManager.destroy();
1664
+ this.motionManager = void 0;
1665
+ this.parallelMotionManager.forEach((m) => m.destroy());
1666
+ this.parallelMotionManager = [];
1667
+ }
1668
+ // noinspection JSValidateJSDoc
1669
+ /**
1670
+ * Updates all active motions for the model and emits lifecycle events.
1671
+ *
1672
+ * This method coordinates the update cycle for both primary and parallel motion managers,
1673
+ * ensuring all animations are synchronized with the current timestamp. It emits events
1674
+ * before and after the update process, allowing external listeners to hook into the motion
1675
+ * lifecycle. The return value indicates whether any motion was actively updated during this cycle.
1676
+ *
1677
+ * @param {object} model - The model instance to apply motion updates to.
1678
+ * @param {number} now - The current timestamp (in milliseconds) used to calculate motion progress.
1679
+ * @returns {boolean} Returns `true` if any motion (primary or parallel) was updated; `false` otherwise.
1680
+ *
1681
+ * @emits beforeMotionUpdate - Triggered before any motion updates are processed.
1682
+ * @emits afterMotionUpdate - Triggered after all motion updates are completed.
1683
+ *
1684
+ */
1685
+ updateMotions(model, now) {
1686
+ this.emit("beforeMotionUpdate");
1687
+ const motionUpdated0 = this.motionManager.update(model, now);
1688
+ const parallelMotionUpdated = this.parallelMotionManager.map((m) => m.update(model, now));
1689
+ const motionUpdated = motionUpdated0 || parallelMotionUpdated.reduce((prev, curr) => prev || curr, false);
1690
+ this.emit("afterMotionUpdate");
1691
+ return motionUpdated;
1692
+ }
1693
+ }
1694
+ const TAG$1 = "XHRLoader";
1695
+ class NetworkError extends Error {
1696
+ constructor(message, url, status, aborted = false) {
1697
+ super(message);
1698
+ this.url = url;
1699
+ this.status = status;
1700
+ this.aborted = aborted;
1701
+ }
1702
+ }
1703
+ const _XHRLoader = class _XHRLoader {
1704
+ /**
1705
+ * Creates a managed XHR.
1706
+ * @param target - If provided, the XHR will be canceled when receiving an "destroy" event from the target.
1707
+ * @param url - The URL.
1708
+ * @param type - The XHR response type.
1709
+ * @param onload - Load listener.
1710
+ * @param onerror - Error handler.
1711
+ */
1712
+ static createXHR(target, url, type, onload, onerror) {
1713
+ const xhr = new XMLHttpRequest();
1714
+ _XHRLoader.allXhrSet.add(xhr);
1715
+ if (target) {
1716
+ let xhrSet = _XHRLoader.xhrMap.get(target);
1717
+ if (!xhrSet) {
1718
+ xhrSet = /* @__PURE__ */ new Set([xhr]);
1719
+ _XHRLoader.xhrMap.set(target, xhrSet);
1720
+ } else {
1721
+ xhrSet.add(xhr);
1722
+ }
1723
+ }
1724
+ xhr.open("GET", url);
1725
+ xhr.responseType = type;
1726
+ xhr.onload = () => {
1727
+ var _a;
1728
+ if ((xhr.status === 200 || xhr.status === 0) && xhr.response) {
1729
+ onload(xhr.response);
1730
+ } else {
1731
+ (_a = xhr.onerror) == null ? void 0 : _a.call(xhr, new ProgressEvent("error"));
1732
+ }
1733
+ };
1734
+ xhr.onerror = () => {
1735
+ logger.warn(
1736
+ TAG$1,
1737
+ `Failed to load resource as ${xhr.responseType} (Status ${xhr.status}): ${url}`
1738
+ );
1739
+ onerror(new NetworkError("Network error.", url, xhr.status));
1740
+ };
1741
+ xhr.onabort = () => onerror(new NetworkError("Aborted.", url, xhr.status, true));
1742
+ xhr.onloadend = () => {
1743
+ var _a;
1744
+ _XHRLoader.allXhrSet.delete(xhr);
1745
+ if (target) {
1746
+ (_a = _XHRLoader.xhrMap.get(target)) == null ? void 0 : _a.delete(xhr);
1747
+ }
1748
+ };
1749
+ return xhr;
1750
+ }
1751
+ /**
1752
+ * Cancels all XHRs related to this target.
1753
+ */
1754
+ static cancelXHRs() {
1755
+ var _a;
1756
+ (_a = _XHRLoader.xhrMap.get(this)) == null ? void 0 : _a.forEach((xhr) => {
1757
+ xhr.abort();
1758
+ _XHRLoader.allXhrSet.delete(xhr);
1759
+ });
1760
+ _XHRLoader.xhrMap.delete(this);
1761
+ }
1762
+ /**
1763
+ * Release all XHRs.
1764
+ */
1765
+ static release() {
1766
+ _XHRLoader.allXhrSet.forEach((xhr) => xhr.abort());
1767
+ _XHRLoader.allXhrSet.clear();
1768
+ _XHRLoader.xhrMap = /* @__PURE__ */ new WeakMap();
1769
+ }
1770
+ };
1771
+ /**
1772
+ * All the created XHRs, keyed by their owners respectively.
1773
+ */
1774
+ __publicField(_XHRLoader, "xhrMap", /* @__PURE__ */ new WeakMap());
1775
+ /**
1776
+ * All the created XHRs as a flat array.
1777
+ */
1778
+ __publicField(_XHRLoader, "allXhrSet", /* @__PURE__ */ new Set());
1779
+ /**
1780
+ * Middleware for Live2DLoader.
1781
+ */
1782
+ __publicField(_XHRLoader, "loader", (context) => {
1783
+ return new Promise((resolve, reject) => {
1784
+ const targetWithEvents = context.target;
1785
+ const cancelListener = context.target && typeof _XHRLoader.cancelXHRs === "function" ? _XHRLoader.cancelXHRs.bind(context.target) : void 0;
1786
+ const xhr = _XHRLoader.createXHR(
1787
+ context.target,
1788
+ context.settings ? context.settings.resolveURL(context.url) : context.url,
1789
+ context.type,
1790
+ (data) => {
1791
+ context.result = data;
1792
+ resolve();
1793
+ },
1794
+ reject
1795
+ );
1796
+ if (context.target && cancelListener) {
1797
+ if (typeof targetWithEvents.listeners === "function" && typeof targetWithEvents.once === "function") {
1798
+ const listeners = targetWithEvents.listeners("destroy");
1799
+ if (!Array.isArray(listeners) || !listeners.includes(cancelListener)) {
1800
+ targetWithEvents.once("destroy", cancelListener);
1801
+ }
1802
+ }
1803
+ }
1804
+ xhr.send();
1805
+ });
1806
+ });
1807
+ let XHRLoader = _XHRLoader;
1808
+ function runMiddlewares(middleware, context) {
1809
+ let index = -1;
1810
+ return dispatch(0);
1811
+ function dispatch(i, err) {
1812
+ if (err) return Promise.reject(err);
1813
+ if (i <= index) return Promise.reject(new Error("next() called multiple times"));
1814
+ index = i;
1815
+ const fn = middleware[i];
1816
+ if (!fn) return Promise.resolve();
1817
+ try {
1818
+ return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
1819
+ } catch (err2) {
1820
+ const error = err2 instanceof Error ? err2 : new Error(String(err2));
1821
+ return Promise.reject(error);
1822
+ }
1823
+ }
1824
+ }
1825
+ class Live2DLoader {
1826
+ /**
1827
+ * Loads a resource.
1828
+ * @return Promise that resolves with the loaded data in a format that's consistent with the specified `type`.
1829
+ */
1830
+ static load(context) {
1831
+ return __async(this, null, function* () {
1832
+ yield runMiddlewares(this.middlewares, context);
1833
+ return context.result;
1834
+ });
1835
+ }
1836
+ }
1837
+ __publicField(Live2DLoader, "middlewares", [XHRLoader.loader]);
1838
+ class CubismLegacyModelSettings extends ModelSettings {
1839
+ constructor(json) {
1840
+ super(json);
1841
+ // files
1842
+ __publicField(this, "moc");
1843
+ __publicField(this, "textures");
1844
+ // metadata
1845
+ __publicField(this, "layout");
1846
+ __publicField(this, "hitAreas");
1847
+ __publicField(this, "initParams");
1848
+ __publicField(this, "initOpacities");
1849
+ // motions
1850
+ __publicField(this, "expressions");
1851
+ __publicField(this, "motions", {});
1852
+ if (!CubismLegacyModelSettings.isValidJSON(json)) {
1853
+ throw new TypeError("Invalid JSON.");
1854
+ }
1855
+ this.moc = json.model;
1856
+ copyArray("string", json, this, "textures", "textures");
1857
+ this.copy(json);
1858
+ }
1859
+ /**
1860
+ * Checks if a JSON object is valid model settings.
1861
+ * @param json
1862
+ */
1863
+ static isValidJSON(json) {
1864
+ if (!json || typeof json !== "object") {
1865
+ return false;
1866
+ }
1867
+ const hasValidTextures = Array.isArray(json.textures) ? json.textures.every((item) => typeof item === "string") : false;
1868
+ return typeof json.model === "string" && hasValidTextures;
1869
+ }
1870
+ /**
1871
+ * Validates and copies *optional* properties from raw JSON.
1872
+ */
1873
+ copy(json) {
1874
+ copyProperty("string", json, this, "name", "name");
1875
+ copyProperty("string", json, this, "pose", "pose");
1876
+ copyProperty("string", json, this, "physics", "physics");
1877
+ copyProperty("object", json, this, "layout", "layout");
1878
+ copyProperty("object", json, this, "motions", "motions");
1879
+ copyArray("object", json, this, "hit_areas", "hitAreas");
1880
+ copyArray("object", json, this, "expressions", "expressions");
1881
+ copyArray("object", json, this, "init_params", "initParams");
1882
+ copyArray("object", json, this, "init_opacities", "initOpacities");
1883
+ const mocStem = this.getFileStem(this.moc);
1884
+ this.setModelName(this.name, mocStem);
1885
+ }
1886
+ replaceFiles(replace) {
1887
+ super.replaceFiles(replace);
1888
+ for (const [group, motions] of Object.entries(this.motions)) {
1889
+ for (let i = 0; i < motions.length; i++) {
1890
+ motions[i].file = replace(motions[i].file, `motions.${group}[${i}].file`);
1891
+ if (motions[i].sound !== void 0) {
1892
+ motions[i].sound = replace(motions[i].sound, `motions.${group}[${i}].sound`);
1893
+ }
1894
+ }
1895
+ }
1896
+ if (this.expressions) {
1897
+ for (let i = 0; i < this.expressions.length; i++) {
1898
+ this.expressions[i].file = replace(this.expressions[i].file, `expressions[${i}].file`);
1899
+ }
1900
+ }
1901
+ }
1902
+ }
1903
+ function createTexture(url, options = {}) {
1904
+ const config2 = loadTextures.config;
1905
+ const previousCrossOrigin = config2 == null ? void 0 : config2.crossOrigin;
1906
+ const previousPreferCreateImageBitmap = config2 == null ? void 0 : config2.preferCreateImageBitmap;
1907
+ const previousPreferWorkers = config2 == null ? void 0 : config2.preferWorkers;
1908
+ if (options.crossOrigin !== void 0 && config2) {
1909
+ config2.crossOrigin = options.crossOrigin;
1910
+ }
1911
+ if (options.preferCreateImageBitmap === false && config2) {
1912
+ config2.preferCreateImageBitmap = false;
1913
+ config2.preferWorkers = false;
1914
+ }
1915
+ return Assets.load(url).catch((error) => {
1916
+ if (error instanceof Error) {
1917
+ throw error;
1918
+ }
1919
+ throw new Error("Texture loading error", { cause: error });
1920
+ }).finally(() => {
1921
+ if (config2) {
1922
+ config2.crossOrigin = previousCrossOrigin != null ? previousCrossOrigin : config2.crossOrigin;
1923
+ if (options.preferCreateImageBitmap === false) {
1924
+ config2.preferCreateImageBitmap = previousPreferCreateImageBitmap != null ? previousPreferCreateImageBitmap : config2.preferCreateImageBitmap;
1925
+ config2.preferWorkers = previousPreferWorkers != null ? previousPreferWorkers : config2.preferWorkers;
1926
+ }
1927
+ }
1928
+ });
1929
+ }
1930
+ function noop() {
1931
+ }
1932
+ const TAG = "Live2DFactory";
1933
+ const urlToJSON = (context, next) => __async(null, null, function* () {
1934
+ if (typeof context.source === "string") {
1935
+ const data = yield Live2DLoader.load({
1936
+ url: context.source,
1937
+ type: "json",
1938
+ target: context.live2dModel
1939
+ });
1940
+ data.url = typeof data.url === "string" ? data.url : context.source;
1941
+ context.source = data;
1942
+ context.live2dModel.emit("settingsJSONLoaded", data);
1943
+ }
1944
+ return next();
1945
+ });
1946
+ const jsonToSettings = (context, next) => __async(null, null, function* () {
1947
+ if (context.source instanceof ModelSettings) {
1948
+ context.settings = context.source;
1949
+ return next();
1950
+ } else if (typeof context.source === "object") {
1951
+ const runtime = Live2DFactory.findRuntime(context.source);
1952
+ if (runtime) {
1953
+ const settings = runtime.createModelSettings(context.source);
1954
+ context.settings = settings;
1955
+ context.live2dModel.emit("settingsLoaded", settings);
1956
+ return next();
1957
+ }
1958
+ }
1959
+ throw new TypeError("Unknown settings format.");
1960
+ });
1961
+ const waitUntilReady = (context, next) => {
1962
+ if (context.settings) {
1963
+ const runtime = Live2DFactory.findRuntime(context.settings);
1964
+ if (runtime) {
1965
+ return runtime.ready().then(() => next());
1966
+ }
1967
+ }
1968
+ return next();
1969
+ };
1970
+ const setupOptionals = (context, next) => __async(null, null, function* () {
1971
+ yield next();
1972
+ const internalModel = context.internalModel;
1973
+ if (internalModel) {
1974
+ const settings = context.settings;
1975
+ const runtime = Live2DFactory.findRuntime(settings);
1976
+ if (runtime) {
1977
+ const tasks = [];
1978
+ const optionalDataType = settings instanceof CubismLegacyModelSettings ? "json" : "arraybuffer";
1979
+ if (settings.pose) {
1980
+ tasks.push(
1981
+ Live2DLoader.load({
1982
+ settings,
1983
+ url: settings.pose,
1984
+ type: optionalDataType,
1985
+ target: internalModel
1986
+ }).then((data) => {
1987
+ internalModel.pose = runtime.createPose(internalModel.coreModel, data);
1988
+ context.live2dModel.emit("poseLoaded", internalModel.pose);
1989
+ }).catch((e) => {
1990
+ context.live2dModel.emit("poseLoadError", e);
1991
+ logger.warn(TAG, "Failed to load pose.", e);
1992
+ })
1993
+ );
1994
+ }
1995
+ if (settings.physics) {
1996
+ tasks.push(
1997
+ Live2DLoader.load({
1998
+ settings,
1999
+ url: settings.physics,
2000
+ type: optionalDataType,
2001
+ target: internalModel
2002
+ }).then((data) => {
2003
+ internalModel.physics = runtime.createPhysics(internalModel.coreModel, data);
2004
+ context.live2dModel.emit("physicsLoaded", internalModel.physics);
2005
+ }).catch((e) => {
2006
+ context.live2dModel.emit("physicsLoadError", e);
2007
+ logger.warn(TAG, "Failed to load physics.", e);
2008
+ })
2009
+ );
2010
+ }
2011
+ if (tasks.length) {
2012
+ yield Promise.all(tasks);
2013
+ }
2014
+ }
2015
+ }
2016
+ });
2017
+ const setupEssentials = (context, next) => __async(null, null, function* () {
2018
+ if (context.settings) {
2019
+ const live2DModel = context.live2dModel;
2020
+ const textureOptions = {
2021
+ crossOrigin: context.options.crossOrigin
2022
+ };
2023
+ if (context.settings instanceof CubismLegacyModelSettings) {
2024
+ textureOptions.preferCreateImageBitmap = false;
2025
+ }
2026
+ const loadingTextures = Promise.all(
2027
+ context.settings.textures.map((tex) => {
2028
+ const url = context.settings.resolveURL(tex);
2029
+ return createTexture(url, textureOptions);
2030
+ })
2031
+ );
2032
+ loadingTextures.catch(noop);
2033
+ yield next();
2034
+ if (context.internalModel) {
2035
+ live2DModel.internalModel = context.internalModel;
2036
+ live2DModel.emit("modelLoaded", context.internalModel);
2037
+ } else {
2038
+ throw new TypeError("Missing internal model.");
2039
+ }
2040
+ live2DModel.textures = yield loadingTextures;
2041
+ live2DModel.emit("textureLoaded", live2DModel.textures);
2042
+ } else {
2043
+ throw new TypeError("Missing settings.");
2044
+ }
2045
+ });
2046
+ const createInternalModel = (context, next) => __async(null, null, function* () {
2047
+ const settings = context.settings;
2048
+ if (settings instanceof ModelSettings) {
2049
+ const runtime = Live2DFactory.findRuntime(settings);
2050
+ if (!runtime) {
2051
+ throw new TypeError("Unknown model settings.");
2052
+ }
2053
+ const modelData = yield Live2DLoader.load({
2054
+ settings,
2055
+ url: settings.moc,
2056
+ type: "arraybuffer",
2057
+ target: context.live2dModel
2058
+ });
2059
+ if (!runtime.isValidMoc(modelData)) {
2060
+ throw new Error("Invalid moc data");
2061
+ }
2062
+ const coreModel = runtime.createCoreModel(modelData);
2063
+ context.internalModel = runtime.createInternalModel(coreModel, settings, context.options);
2064
+ return next();
2065
+ }
2066
+ throw new TypeError("Missing settings.");
2067
+ });
2068
+ const _ZipLoader = class _ZipLoader {
2069
+ static unzip(reader, settings) {
2070
+ return __async(this, null, function* () {
2071
+ const filePaths = yield _ZipLoader.getFilePaths(reader);
2072
+ const requiredFilePaths = [];
2073
+ for (const definedFile of settings.getDefinedFiles()) {
2074
+ const actualPath = decodeURI(resolveURL(settings.url, definedFile));
2075
+ if (filePaths.includes(actualPath)) {
2076
+ requiredFilePaths.push(actualPath);
2077
+ }
2078
+ }
2079
+ const files = yield _ZipLoader.getFiles(reader, requiredFilePaths);
2080
+ for (let i = 0; i < files.length; i++) {
2081
+ const path = requiredFilePaths[i];
2082
+ const file = files[i];
2083
+ Object.defineProperty(file, "webkitRelativePath", {
2084
+ value: path
2085
+ });
2086
+ }
2087
+ return files;
2088
+ });
2089
+ }
2090
+ static createSettings(reader) {
2091
+ return __async(this, null, function* () {
2092
+ const filePaths = yield _ZipLoader.getFilePaths(reader);
2093
+ const settingsFilePath = filePaths.find(
2094
+ (path) => path.endsWith("model.json") || path.endsWith("model3.json")
2095
+ );
2096
+ if (!settingsFilePath) {
2097
+ throw new Error("Settings file not found");
2098
+ }
2099
+ const settingsText = yield _ZipLoader.readText(reader, settingsFilePath);
2100
+ if (!settingsText) {
2101
+ throw new Error("Empty settings file: " + settingsFilePath);
2102
+ }
2103
+ const settingsJSON = JSON.parse(settingsText);
2104
+ settingsJSON.url = settingsFilePath;
2105
+ const runtime = _ZipLoader.live2dFactory.findRuntime(settingsJSON);
2106
+ if (!runtime) {
2107
+ throw new Error("Unknown settings JSON");
2108
+ }
2109
+ return runtime.createModelSettings(settingsJSON);
2110
+ });
2111
+ }
2112
+ static zipReader(data, url) {
2113
+ return Promise.reject(new Error("Not implemented"));
2114
+ }
2115
+ static getFilePaths(reader) {
2116
+ return Promise.reject(new Error("Not implemented"));
2117
+ }
2118
+ static getFiles(reader, paths) {
2119
+ return Promise.reject(new Error("Not implemented"));
2120
+ }
2121
+ static readText(reader, path) {
2122
+ return Promise.reject(new Error("Not implemented"));
2123
+ }
2124
+ static releaseReader(reader) {
2125
+ }
2126
+ };
2127
+ // will be set by Live2DFactory
2128
+ __publicField(_ZipLoader, "live2dFactory");
2129
+ __publicField(_ZipLoader, "ZIP_PROTOCOL", "zip://");
2130
+ __publicField(_ZipLoader, "uid", 0);
2131
+ __publicField(_ZipLoader, "factory", (context, next) => __async(null, null, function* () {
2132
+ const source = context.source;
2133
+ let sourceURL;
2134
+ let zipBlob;
2135
+ let settings;
2136
+ if (typeof source === "string" && (source.endsWith(".zip") || source.startsWith(_ZipLoader.ZIP_PROTOCOL))) {
2137
+ if (source.startsWith(_ZipLoader.ZIP_PROTOCOL)) {
2138
+ sourceURL = source.slice(_ZipLoader.ZIP_PROTOCOL.length);
2139
+ } else {
2140
+ sourceURL = source;
2141
+ }
2142
+ zipBlob = yield Live2DLoader.load({
2143
+ url: sourceURL,
2144
+ type: "blob",
2145
+ target: context.live2dModel
2146
+ });
2147
+ } else if (Array.isArray(source) && source.length === 1 && source[0] instanceof File && source[0].name.endsWith(".zip")) {
2148
+ zipBlob = source[0];
2149
+ sourceURL = URL.createObjectURL(zipBlob);
2150
+ settings = source.settings;
2151
+ }
2152
+ if (zipBlob) {
2153
+ if (!zipBlob.size) {
2154
+ throw new Error("Empty zip file");
2155
+ }
2156
+ const reader = yield _ZipLoader.zipReader(zipBlob, sourceURL);
2157
+ if (!settings) {
2158
+ settings = yield _ZipLoader.createSettings(reader);
2159
+ }
2160
+ settings._objectURL = _ZipLoader.ZIP_PROTOCOL + _ZipLoader.uid + "/" + settings.url;
2161
+ const files = yield _ZipLoader.unzip(reader, settings);
2162
+ files.settings = settings;
2163
+ context.source = files;
2164
+ if (sourceURL.startsWith("blob:")) {
2165
+ context.live2dModel.once("modelLoaded", (internalModel) => {
2166
+ internalModel.once("destroy", function() {
2167
+ URL.revokeObjectURL(sourceURL);
2168
+ });
2169
+ });
2170
+ }
2171
+ _ZipLoader.releaseReader(reader);
2172
+ }
2173
+ return next();
2174
+ }));
2175
+ let ZipLoader = _ZipLoader;
2176
+ const _FileLoader = class _FileLoader {
2177
+ /**
2178
+ * Resolves the path of a resource file to the object URL.
2179
+ * @param settingsURL - Object URL of the settings file.
2180
+ * @param filePath - Resource file path.
2181
+ * @return Resolved object URL.
2182
+ */
2183
+ static resolveURL(settingsURL, filePath) {
2184
+ var _a;
2185
+ const resolved = (_a = _FileLoader.filesMap[settingsURL]) == null ? void 0 : _a[filePath];
2186
+ if (resolved === void 0) {
2187
+ throw new Error("Cannot find this file from uploaded files: " + filePath);
2188
+ }
2189
+ return resolved;
2190
+ }
2191
+ /**
2192
+ * Consumes the files by storing their object URLs. Files not defined in the settings will be ignored.
2193
+ */
2194
+ static upload(files, settings) {
2195
+ const fileMap = {};
2196
+ for (const definedFile of settings.getDefinedFiles()) {
2197
+ const actualPath = decodeURI(resolveURL(settings.url, definedFile));
2198
+ const actualFile = files.find((file) => file.webkitRelativePath === actualPath);
2199
+ if (actualFile) {
2200
+ fileMap[definedFile] = URL.createObjectURL(actualFile);
2201
+ }
2202
+ }
2203
+ _FileLoader.filesMap[settings._objectURL] = fileMap;
2204
+ }
2205
+ /**
2206
+ * Creates a ModelSettings by given files.
2207
+ * @return Promise that resolves with the created ModelSettings.
2208
+ */
2209
+ static createSettings(files) {
2210
+ return __async(this, null, function* () {
2211
+ const settingsFile = files.find(
2212
+ (file) => file.name.endsWith("model.json") || file.name.endsWith("model3.json")
2213
+ );
2214
+ if (!settingsFile) {
2215
+ throw new TypeError("Settings file not found");
2216
+ }
2217
+ const settingsText = yield _FileLoader.readText(settingsFile);
2218
+ const settingsJSON = JSON.parse(settingsText);
2219
+ settingsJSON.url = settingsFile.webkitRelativePath;
2220
+ const runtime = Live2DFactory.findRuntime(settingsJSON);
2221
+ if (!runtime) {
2222
+ throw new Error("Unknown settings JSON");
2223
+ }
2224
+ const settings = runtime.createModelSettings(settingsJSON);
2225
+ settings._objectURL = URL.createObjectURL(settingsFile);
2226
+ return settings;
2227
+ });
2228
+ }
2229
+ /**
2230
+ * Reads a file as text in UTF-8.
2231
+ */
2232
+ static readText(file) {
2233
+ return __async(this, null, function* () {
2234
+ return new Promise((resolve, reject) => {
2235
+ const reader = new FileReader();
2236
+ reader.onload = () => resolve(reader.result);
2237
+ reader.onerror = reject;
2238
+ reader.readAsText(file, "utf8");
2239
+ });
2240
+ });
2241
+ }
2242
+ };
2243
+ // will be set by Live2DFactory
2244
+ __publicField(_FileLoader, "live2dFactory");
2245
+ /**
2246
+ * Stores all the object URLs of uploaded files.
2247
+ */
2248
+ __publicField(_FileLoader, "filesMap", {});
2249
+ /**
2250
+ * Middleware for Live2DFactory.
2251
+ */
2252
+ __publicField(_FileLoader, "factory", (context, next) => __async(null, null, function* () {
2253
+ if (Array.isArray(context.source) && context.source[0] instanceof File) {
2254
+ const files = context.source;
2255
+ let settings = files.settings;
2256
+ if (!settings) {
2257
+ settings = yield _FileLoader.createSettings(files);
2258
+ } else if (!settings._objectURL) {
2259
+ throw new Error('"_objectURL" must be specified in ModelSettings');
2260
+ }
2261
+ settings.validateFiles(files.map((file) => encodeURI(file.webkitRelativePath)));
2262
+ _FileLoader.upload(files, settings);
2263
+ settings.resolveURL = function(url) {
2264
+ return _FileLoader.resolveURL(this._objectURL, url);
2265
+ };
2266
+ context.source = settings;
2267
+ context.live2dModel.once("modelLoaded", (internalModel) => {
2268
+ internalModel.once("destroy", function() {
2269
+ const objectURL = this.settings._objectURL;
2270
+ URL.revokeObjectURL(objectURL);
2271
+ if (_FileLoader.filesMap[objectURL]) {
2272
+ for (const resourceObjectURL of Object.values(_FileLoader.filesMap[objectURL])) {
2273
+ URL.revokeObjectURL(resourceObjectURL);
2274
+ }
2275
+ }
2276
+ delete _FileLoader.filesMap[objectURL];
2277
+ });
2278
+ });
2279
+ }
2280
+ return next();
2281
+ }));
2282
+ let FileLoader = _FileLoader;
2283
+ const _Live2DFactory = class _Live2DFactory {
2284
+ /**
2285
+ * Registers a Live2DRuntime.
2286
+ */
2287
+ static registerRuntime(runtime) {
2288
+ _Live2DFactory.runtimes.push(runtime);
2289
+ _Live2DFactory.runtimes.sort((a, b) => b.version - a.version);
2290
+ }
2291
+ /**
2292
+ * Finds a runtime that matches given source.
2293
+ * @param source - Either a settings JSON object or a ModelSettings instance.
2294
+ * @return The Live2DRuntime, or undefined if not found.
2295
+ */
2296
+ static findRuntime(source) {
2297
+ for (const runtime of _Live2DFactory.runtimes) {
2298
+ if (runtime.test(source)) {
2299
+ return runtime;
2300
+ }
2301
+ }
2302
+ }
2303
+ /**
2304
+ * Sets up a Live2DModel, populating it with all defined resources.
2305
+ * @param live2dModel - The Live2DModel instance.
2306
+ * @param source - Can be one of: settings file URL, settings JSON object, ModelSettings instance.
2307
+ * @param options - Options for the process.
2308
+ * @return Promise that resolves when all resources have been loaded, rejects when error occurs.
2309
+ */
2310
+ static setupLive2DModel(live2dModel, source, options) {
2311
+ return __async(this, null, function* () {
2312
+ const textureLoaded = new Promise((resolve) => live2dModel.once("textureLoaded", resolve));
2313
+ const modelLoaded = new Promise((resolve) => live2dModel.once("modelLoaded", resolve));
2314
+ const readyEventEmitted = Promise.all([textureLoaded, modelLoaded]).then(
2315
+ () => live2dModel.emit("ready")
2316
+ );
2317
+ yield runMiddlewares(_Live2DFactory.live2DModelMiddlewares, {
2318
+ live2dModel,
2319
+ source,
2320
+ options: options || {}
2321
+ });
2322
+ yield readyEventEmitted;
2323
+ live2dModel.emit("load");
2324
+ });
2325
+ }
2326
+ /**
2327
+ * Loads a Motion and registers the task to {@link motionTasksMap}. The task will be automatically
2328
+ * canceled when its owner - the MotionManager instance - has been destroyed.
2329
+ * @param motionManager - MotionManager that owns this Motion.
2330
+ * @param group - The motion group.
2331
+ * @param index - Index in the motion group.
2332
+ * @return Promise that resolves with the Motion, or with undefined if it can't be loaded.
2333
+ */
2334
+ static loadMotion(motionManager, group, index) {
2335
+ var _a, _b;
2336
+ const handleError = (e) => motionManager.emit("motionLoadError", group, index, e);
2337
+ try {
2338
+ const definition = (_a = motionManager.definitions[group]) == null ? void 0 : _a[index];
2339
+ if (!definition) {
2340
+ return Promise.resolve(void 0);
2341
+ }
2342
+ motionManager.once("destroy", () => _Live2DFactory.releaseMotionTasks(motionManager));
2343
+ let tasks = _Live2DFactory.motionTasksMap.get(motionManager);
2344
+ if (!tasks) {
2345
+ tasks = {};
2346
+ _Live2DFactory.motionTasksMap.set(motionManager, tasks);
2347
+ }
2348
+ let taskGroup = tasks[group];
2349
+ if (!taskGroup) {
2350
+ taskGroup = [];
2351
+ tasks[group] = taskGroup;
2352
+ }
2353
+ const path = motionManager.getMotionFile(definition);
2354
+ (_b = taskGroup[index]) != null ? _b : taskGroup[index] = Live2DLoader.load({
2355
+ url: path,
2356
+ settings: motionManager.settings,
2357
+ type: motionManager.motionDataType,
2358
+ target: motionManager
2359
+ }).then((data) => {
2360
+ var _a2;
2361
+ const taskGroup2 = (_a2 = _Live2DFactory.motionTasksMap.get(motionManager)) == null ? void 0 : _a2[group];
2362
+ if (taskGroup2) {
2363
+ taskGroup2[index] = void 0;
2364
+ }
2365
+ const motionData = data;
2366
+ const motion = motionManager.createMotion(motionData, group, definition);
2367
+ motionManager.emit("motionLoaded", group, index, motion);
2368
+ return motion;
2369
+ }).catch((e) => {
2370
+ logger.warn(motionManager.tag, `Failed to load motion: ${path}
2371
+ `, e);
2372
+ handleError(e);
2373
+ });
2374
+ return taskGroup[index];
2375
+ } catch (e) {
2376
+ logger.warn(motionManager.tag, `Failed to load motion at "${group}"[${index}]
2377
+ `, e);
2378
+ handleError(e);
2379
+ }
2380
+ return Promise.resolve(void 0);
2381
+ }
2382
+ /**
2383
+ * Loads an Expression and registers the task to {@link expressionTasksMap}. The task will be automatically
2384
+ * canceled when its owner - the ExpressionManager instance - has been destroyed.
2385
+ * @param expressionManager - ExpressionManager that owns this Expression.
2386
+ * @param index - Index of the Expression.
2387
+ * @return Promise that resolves with the Expression, or with undefined if it can't be loaded.
2388
+ */
2389
+ static loadExpression(expressionManager, index) {
2390
+ var _a, _b;
2391
+ const handleError = (e) => expressionManager.emit("expressionLoadError", index, e);
2392
+ try {
2393
+ const definition = expressionManager.definitions[index];
2394
+ if (!definition) {
2395
+ return Promise.resolve(void 0);
2396
+ }
2397
+ expressionManager.once(
2398
+ "destroy",
2399
+ () => _Live2DFactory.releaseExpressionTasks(expressionManager)
2400
+ );
2401
+ let tasks = _Live2DFactory.expressionTasksMap.get(expressionManager);
2402
+ if (!tasks) {
2403
+ tasks = [];
2404
+ _Live2DFactory.expressionTasksMap.set(expressionManager, tasks);
2405
+ }
2406
+ const path = expressionManager.getExpressionFile(definition);
2407
+ const responseType = (_a = expressionManager.expressionDataType) != null ? _a : "json";
2408
+ (_b = tasks[index]) != null ? _b : tasks[index] = Live2DLoader.load({
2409
+ url: path,
2410
+ settings: expressionManager.settings,
2411
+ type: responseType,
2412
+ target: expressionManager
2413
+ }).then((data) => {
2414
+ const tasks2 = _Live2DFactory.expressionTasksMap.get(expressionManager);
2415
+ if (tasks2) {
2416
+ tasks2[index] = void 0;
2417
+ }
2418
+ const expressionData = data;
2419
+ const expression = expressionManager.createExpression(expressionData, definition);
2420
+ expressionManager.emit("expressionLoaded", index, expression);
2421
+ return expression;
2422
+ }).catch((e) => {
2423
+ logger.warn(expressionManager.tag, `Failed to load expression: ${path}
2424
+ `, e);
2425
+ handleError(e);
2426
+ });
2427
+ return tasks[index];
2428
+ } catch (e) {
2429
+ logger.warn(expressionManager.tag, `Failed to load expression at [${index}]
2430
+ `, e);
2431
+ handleError(e);
2432
+ }
2433
+ return Promise.resolve(void 0);
2434
+ }
2435
+ static releaseMotionTasks(motionManager) {
2436
+ _Live2DFactory.motionTasksMap.delete(motionManager);
2437
+ }
2438
+ static releaseExpressionTasks(expressionManager) {
2439
+ _Live2DFactory.expressionTasksMap.delete(expressionManager);
2440
+ }
2441
+ };
2442
+ /**
2443
+ * All registered runtimes, sorted by versions in descending order.
2444
+ */
2445
+ __publicField(_Live2DFactory, "runtimes", []);
2446
+ __publicField(_Live2DFactory, "urlToJSON", urlToJSON);
2447
+ __publicField(_Live2DFactory, "jsonToSettings", jsonToSettings);
2448
+ __publicField(_Live2DFactory, "waitUntilReady", waitUntilReady);
2449
+ __publicField(_Live2DFactory, "setupOptionals", setupOptionals);
2450
+ __publicField(_Live2DFactory, "setupEssentials", setupEssentials);
2451
+ __publicField(_Live2DFactory, "createInternalModel", createInternalModel);
2452
+ /**
2453
+ * Middlewares to run through when setting up a Live2DModel.
2454
+ */
2455
+ __publicField(_Live2DFactory, "live2DModelMiddlewares", [
2456
+ ZipLoader.factory,
2457
+ FileLoader.factory,
2458
+ urlToJSON,
2459
+ jsonToSettings,
2460
+ waitUntilReady,
2461
+ setupOptionals,
2462
+ setupEssentials,
2463
+ createInternalModel
2464
+ ]);
2465
+ /**
2466
+ * load tasks of each motion. The structure of each value in this map
2467
+ * is the same as respective {@link MotionManager.definitions}.
2468
+ */
2469
+ __publicField(_Live2DFactory, "motionTasksMap", /* @__PURE__ */ new WeakMap());
2470
+ /**
2471
+ * Load tasks of each expression.
2472
+ */
2473
+ __publicField(_Live2DFactory, "expressionTasksMap", /* @__PURE__ */ new WeakMap());
2474
+ let Live2DFactory = _Live2DFactory;
2475
+ MotionManager.prototype["_loadMotion"] = function(group, index) {
2476
+ return Live2DFactory.loadMotion(this, group, index);
2477
+ };
2478
+ ExpressionManager.prototype["_loadExpression"] = function(index) {
2479
+ return Live2DFactory.loadExpression(this, index);
2480
+ };
2481
+ FileLoader["live2dFactory"] = Live2DFactory;
2482
+ ZipLoader["live2dFactory"] = Live2DFactory;
2483
+ const _Automator = class _Automator {
2484
+ constructor(model, {
2485
+ autoUpdate = true,
2486
+ autoHitTest = true,
2487
+ autoFocus = true,
2488
+ autoInteract,
2489
+ ticker
2490
+ } = {}) {
2491
+ __publicField(this, "model");
2492
+ __publicField(this, "destroyed", false);
2493
+ __publicField(this, "_ticker");
2494
+ __publicField(this, "_autoUpdate", false);
2495
+ __publicField(this, "_autoHitTest", false);
2496
+ __publicField(this, "_autoFocus", false);
2497
+ var _a;
2498
+ ticker != null ? ticker : ticker = (_a = _Automator.defaultTicker) != null ? _a : typeof PIXI !== "undefined" ? PIXI.Ticker.shared : Ticker.shared;
2499
+ if (autoInteract !== void 0) {
2500
+ autoHitTest = autoInteract;
2501
+ autoFocus = autoInteract;
2502
+ logger.warn(
2503
+ model.tag,
2504
+ "options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead."
2505
+ );
2506
+ }
2507
+ this.model = model;
2508
+ this.ticker = ticker;
2509
+ this.autoUpdate = autoUpdate;
2510
+ this.autoHitTest = autoHitTest;
2511
+ this.autoFocus = autoFocus;
2512
+ if (autoHitTest || autoFocus) {
2513
+ this.model.eventMode = "static";
2514
+ }
2515
+ }
2516
+ get ticker() {
2517
+ return this._ticker;
2518
+ }
2519
+ set ticker(ticker) {
2520
+ var _a, _b;
2521
+ if (this._ticker) {
2522
+ this._ticker.remove(onTickerUpdate, this);
2523
+ }
2524
+ this._ticker = ticker;
2525
+ if (this._autoUpdate) {
2526
+ (_a = this._ticker) == null ? void 0 : _a.add(onTickerUpdate, this);
2527
+ (_b = this._ticker) == null ? void 0 : _b.start();
2528
+ }
2529
+ }
2530
+ /**
2531
+ * @see {@link AutomatorOptions.autoUpdate}
2532
+ */
2533
+ get autoUpdate() {
2534
+ return this._autoUpdate;
2535
+ }
2536
+ set autoUpdate(autoUpdate) {
2537
+ var _a;
2538
+ if (this.destroyed) {
2539
+ return;
2540
+ }
2541
+ if (autoUpdate) {
2542
+ if (this._ticker) {
2543
+ this._ticker.add(onTickerUpdate, this);
2544
+ this._autoUpdate = true;
2545
+ } else {
2546
+ logger.warn(
2547
+ this.model.tag,
2548
+ "No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."
2549
+ );
2550
+ }
2551
+ } else {
2552
+ (_a = this._ticker) == null ? void 0 : _a.remove(onTickerUpdate, this);
2553
+ this._autoUpdate = false;
2554
+ }
2555
+ }
2556
+ /**
2557
+ * @see {@link AutomatorOptions.autoHitTest}
2558
+ */
2559
+ get autoHitTest() {
2560
+ return this._autoHitTest;
2561
+ }
2562
+ set autoHitTest(autoHitTest) {
2563
+ if (autoHitTest !== this.autoHitTest) {
2564
+ if (autoHitTest) {
2565
+ this.model.on("pointertap", onTap, this);
2566
+ } else {
2567
+ this.model.off("pointertap", onTap, this);
2568
+ }
2569
+ this._autoHitTest = autoHitTest;
2570
+ }
2571
+ }
2572
+ /**
2573
+ * @see {@link AutomatorOptions.autoFocus}
2574
+ */
2575
+ get autoFocus() {
2576
+ return this._autoFocus;
2577
+ }
2578
+ set autoFocus(autoFocus) {
2579
+ if (autoFocus !== this.autoFocus) {
2580
+ if (autoFocus) {
2581
+ this.model.on("globalpointermove", onPointerMove, this);
2582
+ this.model.on("pointermove", onPointerMove, this);
2583
+ } else {
2584
+ this.model.off("globalpointermove", onPointerMove, this);
2585
+ this.model.off("pointermove", onPointerMove, this);
2586
+ }
2587
+ this._autoFocus = autoFocus;
2588
+ }
2589
+ }
2590
+ /**
2591
+ * @see {@link AutomatorOptions.autoInteract}
2592
+ */
2593
+ get autoInteract() {
2594
+ return this._autoHitTest && this._autoFocus;
2595
+ }
2596
+ set autoInteract(autoInteract) {
2597
+ this.autoHitTest = autoInteract;
2598
+ this.autoFocus = autoInteract;
2599
+ }
2600
+ onTickerUpdate() {
2601
+ const deltaMS = this.ticker.deltaMS;
2602
+ this.model.update(deltaMS);
2603
+ }
2604
+ onTap(event) {
2605
+ this.model.tap(event.global.x, event.global.y);
2606
+ }
2607
+ onPointerMove(event) {
2608
+ this.model.focus(event.global.x, event.global.y);
2609
+ }
2610
+ destroy() {
2611
+ this.autoFocus = false;
2612
+ this.autoHitTest = false;
2613
+ this.autoUpdate = false;
2614
+ this.ticker = void 0;
2615
+ this.destroyed = true;
2616
+ }
2617
+ };
2618
+ __publicField(_Automator, "defaultTicker");
2619
+ let Automator = _Automator;
2620
+ function onTickerUpdate() {
2621
+ this.onTickerUpdate();
2622
+ }
2623
+ function onTap(event) {
2624
+ this.onTap(event);
2625
+ }
2626
+ function onPointerMove(event) {
2627
+ this.onPointerMove(event);
2628
+ }
2629
+ class Live2DTransform extends Transform {
2630
+ }
2631
+ const tempPoint = new Point();
2632
+ const tempMatrix = new Matrix();
2633
+ const tempWorldMatrix = new Matrix();
2634
+ const tempDrawableBounds = { x: 0, y: 0, width: 0, height: 0 };
2635
+ const tempModelBounds = new Bounds();
2636
+ class Live2DPipe {
2637
+ constructor(renderer) {
2638
+ this.renderer = renderer;
2639
+ }
2640
+ execute(model) {
2641
+ if (!model.visible || model.alpha <= 0) {
2642
+ return;
2643
+ }
2644
+ model.renderLive2D(this.renderer);
2645
+ }
2646
+ updateRenderable() {
2647
+ }
2648
+ destroy() {
2649
+ }
2650
+ }
2651
+ function ensureLive2DPipe(renderer) {
2652
+ const r = renderer;
2653
+ if (!r.renderPipes.live2d) {
2654
+ r.renderPipes.live2d = new Live2DPipe(renderer);
2655
+ }
2656
+ }
2657
+ class Live2DModel extends Container {
2658
+ /**
2659
+ * Creates a new Live2DModel instance.
2660
+ * @param options - Options for Live2DModel and Automator.
2661
+ */
2662
+ constructor(options) {
2663
+ super();
2664
+ /** @internal */
2665
+ __publicField(this, "renderPipeId", "live2d");
2666
+ /**
2667
+ * Tag for logging.
2668
+ * @type {string}
2669
+ */
2670
+ __publicField(this, "tag", "Live2DModel(uninitialized)");
2671
+ /**
2672
+ * The internal model. Though typed as non-nullable, it'll be undefined until the "ready" event is emitted.
2673
+ */
2674
+ __publicField(this, "internalModel");
2675
+ /**
2676
+ * Pixi textures.
2677
+ * @type {Texture[]}
2678
+ */
2679
+ __publicField(this, "textures", []);
2680
+ /** @override
2681
+ * The Live2DTransform instance for this model.
2682
+ */
2683
+ __publicField(this, "transform", new Live2DTransform());
2684
+ /**
2685
+ * The anchor behaves like the one in `PIXI.Sprite`, where `(0, 0)` means the top left
2686
+ * and `(1, 1)` means the bottom right.
2687
+ * @type {ObservablePoint}
2688
+ */
2689
+ __publicField(this, "anchor");
2690
+ /** @internal */
2691
+ __publicField(this, "_bounds", new Bounds());
2692
+ /** @internal */
2693
+ __publicField(this, "_boundsDirty", true);
2694
+ /** @internal */
2695
+ __publicField(this, "_boundsRetryAfterDraw", false);
2696
+ /**
2697
+ * An ID of Gl context that syncs with `renderer.CONTEXT_UID`. Used to check if the GL context has changed.
2698
+ * @protected
2699
+ * @type {number}
2700
+ */
2701
+ __publicField(this, "gl", null);
2702
+ /**
2703
+ * Elapsed time in milliseconds since created.
2704
+ * @type {DOMHighResTimeStamp}
2705
+ */
2706
+ __publicField(this, "elapsedTime", 0);
2707
+ /**
2708
+ * Elapsed time in milliseconds from last frame to this frame.
2709
+ * @type {DOMHighResTimeStamp}
2710
+ */
2711
+ __publicField(this, "deltaTime", 0);
2712
+ /**
2713
+ * The Automator instance that controls model automation.
2714
+ * @type {Automator}
2715
+ */
2716
+ __publicField(this, "automator");
2717
+ __publicField(this, "currentGlId", 0);
2718
+ /**
2719
+ * Renders the Live2DModel to the renderer.
2720
+ * @param renderer - The PixiJS Renderer instance.
2721
+ */
2722
+ __publicField(this, "renderLive2D", (renderer) => {
2723
+ var _a, _b, _c, _d, _e;
2724
+ if (!(renderer instanceof WebGLRenderer)) {
2725
+ throw new Error(`Renderer is not supported`);
2726
+ }
2727
+ renderer.geometry.resetState();
2728
+ renderer.shader.resetState();
2729
+ renderer.texture.resetState();
2730
+ let shouldUpdateTexture = false;
2731
+ if (this.gl !== renderer.gl) {
2732
+ this.gl = renderer.gl;
2733
+ this.internalModel.updateWebGLContext(renderer.gl, this.generateUID());
2734
+ shouldUpdateTexture = true;
2735
+ }
2736
+ for (let i = 0; i < this.textures.length; i++) {
2737
+ const texture = this.textures[i];
2738
+ const hasGlSource = Boolean(texture.source._gpuData[renderer.uid]);
2739
+ if (shouldUpdateTexture || !hasGlSource) {
2740
+ renderer.gl.pixelStorei(
2741
+ WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,
2742
+ this.internalModel.textureFlipY
2743
+ );
2744
+ renderer.texture.bind(texture, 0);
2745
+ }
2746
+ this.internalModel.bindTexture(i, renderer.texture.getGlSource(texture.source).texture);
2747
+ }
2748
+ const viewport = renderer.renderTarget.viewport;
2749
+ const renderTarget = renderer.renderTarget.renderTarget;
2750
+ let viewportY = viewport.y;
2751
+ if (renderTarget == null ? void 0 : renderTarget.isRoot) {
2752
+ const pixelHeight = renderTarget.colorTexture.source.pixelHeight;
2753
+ viewportY = pixelHeight - viewport.height - viewport.y;
2754
+ }
2755
+ this.internalModel.viewport = [viewport.x, viewportY, viewport.width, viewport.height];
2756
+ const frameDelta = this.deltaTime;
2757
+ this.deltaTime = 0;
2758
+ if (frameDelta) {
2759
+ this.internalModel.update(frameDelta, this.elapsedTime);
2760
+ }
2761
+ const { projectionMatrix, offset } = renderer.globalUniforms.globalUniformData;
2762
+ const adjustedWorld = tempWorldMatrix.copyFrom(this.worldTransform);
2763
+ adjustedWorld.tx -= (_a = offset == null ? void 0 : offset.x) != null ? _a : 0;
2764
+ adjustedWorld.ty -= (_b = offset == null ? void 0 : offset.y) != null ? _b : 0;
2765
+ const internalTransform = tempMatrix.copyFrom(projectionMatrix).append(adjustedWorld);
2766
+ this.internalModel.updateTransform(internalTransform);
2767
+ this.internalModel.draw(renderer.gl);
2768
+ if (this._boundsRetryAfterDraw) {
2769
+ this.updateDrawableBounds();
2770
+ }
2771
+ renderer.state.resetState();
2772
+ renderer.texture.resetState();
2773
+ const clearColor = (_c = renderer.renderTarget) == null ? void 0 : _c.defaultClearColor;
2774
+ const clearColorCache = (_e = (_d = renderer.renderTarget) == null ? void 0 : _d.adaptor) == null ? void 0 : _e._clearColorCache;
2775
+ if (clearColor) {
2776
+ renderer.gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
2777
+ if (clearColorCache) {
2778
+ clearColorCache[0] = clearColor[0];
2779
+ clearColorCache[1] = clearColor[1];
2780
+ clearColorCache[2] = clearColor[2];
2781
+ clearColorCache[3] = clearColor[3];
2782
+ }
2783
+ }
2784
+ });
2785
+ this.anchor = new ObservablePoint(
2786
+ {
2787
+ _onUpdate: () => this.onAnchorChange()
2788
+ },
2789
+ 0,
2790
+ 0
2791
+ );
2792
+ this.automator = new Automator(this, options);
2793
+ this.once("modelLoaded", () => this.initializeOnModelLoad(options));
2794
+ }
2795
+ /** @internal */
2796
+ get isRenderable() {
2797
+ return true;
2798
+ }
2799
+ /** @internal */
2800
+ get canBundle() {
2801
+ return false;
2802
+ }
2803
+ /**
2804
+ * Creates a Live2DModel from given source.
2805
+ * @param source - Can be one of: settings file URL, settings JSON object, ModelSettings instance.
2806
+ * @param options - Options for the creation.
2807
+ * @return Promise that resolves with the Live2DModel.
2808
+ */
2809
+ static from(source, options) {
2810
+ return __async(this, null, function* () {
2811
+ const model = new this(options);
2812
+ yield Live2DFactory.setupLive2DModel(model, source, options);
2813
+ return model;
2814
+ });
2815
+ }
2816
+ /**
2817
+ * Synchronous version of `Live2DModel.from()`. This method immediately returns a Live2DModel instance,
2818
+ * whose resources have not been loaded. Therefore, this model can't be manipulated or rendered
2819
+ * until the "load" event has been emitted.
2820
+ *
2821
+ * ```js
2822
+ * // no `await` here as it's not a Promise
2823
+ * const model = Live2DModel.fromSync('shizuku.model.json');
2824
+ *
2825
+ * // these will cause errors!
2826
+ * // app.stage.addChild(model);
2827
+ * // model.motion('tap_body');
2828
+ *
2829
+ * model.once('load', () => {
2830
+ * // now it's safe
2831
+ * app.stage.addChild(model);
2832
+ * model.motion('tap_body');
2833
+ * });
2834
+ * ```
2835
+ * @param source - Model source, can be a file path, JSON object, or ModelSettings instance.
2836
+ * @param options - Options for the model creation.
2837
+ * @returns The created Live2DModel instance.
2838
+ */
2839
+ static fromSync(source, options) {
2840
+ const model = new this(options);
2841
+ void Live2DFactory.setupLive2DModel(model, source, options).then(() => {
2842
+ var _a;
2843
+ return (_a = options == null ? void 0 : options.onLoad) == null ? void 0 : _a.call(options);
2844
+ }).catch((err) => {
2845
+ var _a;
2846
+ return (_a = options == null ? void 0 : options.onError) == null ? void 0 : _a.call(options, err);
2847
+ });
2848
+ return model;
2849
+ }
2850
+ /**
2851
+ * Registers the class of `PIXI.Ticker` for auto updating.
2852
+ * @deprecated Use {@link Live2DModelOptions.ticker} instead.
2853
+ * @param tickerClass - The Ticker class to be registered.
2854
+ */
2855
+ static registerTicker(tickerClass) {
2856
+ Automator["defaultTicker"] = tickerClass.shared;
2857
+ }
2858
+ /** @internal */
2859
+ get bounds() {
2860
+ if (!this.internalModel) {
2861
+ this._bounds.set(0, 0, 0, 0);
2862
+ return this._bounds;
2863
+ }
2864
+ if (this._boundsDirty) {
2865
+ this.updateDrawableBounds();
2866
+ }
2867
+ return this._bounds;
2868
+ }
2869
+ updateDrawableBounds() {
2870
+ if (!this.internalModel) {
2871
+ this._bounds.set(0, 0, 0, 0);
2872
+ this._boundsDirty = false;
2873
+ return;
2874
+ }
2875
+ const drawableIds = this.internalModel.getDrawableIDs();
2876
+ tempModelBounds.clear();
2877
+ for (let i = 0; i < drawableIds.length; i++) {
2878
+ const drawableId = drawableIds[i];
2879
+ const drawableIndex = this.internalModel.getDrawableIndex(drawableId);
2880
+ if (drawableIndex < 0) {
2881
+ continue;
2882
+ }
2883
+ const drawableBounds = this.internalModel.getDrawableBounds(drawableIndex, tempDrawableBounds);
2884
+ if (!Number.isFinite(drawableBounds.x) || !Number.isFinite(drawableBounds.y) || !Number.isFinite(drawableBounds.width) || !Number.isFinite(drawableBounds.height)) {
2885
+ continue;
2886
+ }
2887
+ tempModelBounds.addFrame(
2888
+ drawableBounds.x,
2889
+ drawableBounds.y,
2890
+ drawableBounds.x + drawableBounds.width,
2891
+ drawableBounds.y + drawableBounds.height,
2892
+ Matrix.IDENTITY
2893
+ );
2894
+ }
2895
+ this._bounds.clear();
2896
+ if (tempModelBounds.isValid && tempModelBounds.isPositive) {
2897
+ this._bounds.addFrame(
2898
+ tempModelBounds.minX,
2899
+ tempModelBounds.minY,
2900
+ tempModelBounds.maxX,
2901
+ tempModelBounds.maxY,
2902
+ this.internalModel.localTransform
2903
+ );
2904
+ this._boundsRetryAfterDraw = false;
2905
+ } else {
2906
+ const width = this.internalModel.originalWidth || this.internalModel.width;
2907
+ const height = this.internalModel.originalHeight || this.internalModel.height;
2908
+ this._bounds.addFrame(0, 0, width, height, this.internalModel.localTransform);
2909
+ this._boundsRetryAfterDraw = true;
2910
+ }
2911
+ this._boundsDirty = false;
2912
+ }
2913
+ generateUID() {
2914
+ return ++this.currentGlId;
2915
+ }
2916
+ /**
2917
+ * Insert this model into Pixi's instruction set so zIndex ordering works with other objects.
2918
+ */
2919
+ collectRenderables(instructionSet, renderer, currentLayer) {
2920
+ var _a, _b, _c, _d;
2921
+ if (this.parentRenderLayer && this.parentRenderLayer !== currentLayer) {
2922
+ return;
2923
+ }
2924
+ if (this.globalDisplayStatus < 7) {
2925
+ return;
2926
+ }
2927
+ if (!this.includeInBuild) {
2928
+ return;
2929
+ }
2930
+ if (this.sortableChildren) {
2931
+ this.sortChildren();
2932
+ }
2933
+ ensureLive2DPipe(renderer);
2934
+ const renderPipes = renderer.renderPipes;
2935
+ const addRenderable = () => {
2936
+ var _a2, _b2;
2937
+ (_b2 = (_a2 = renderPipes.batch) == null ? void 0 : _a2.break) == null ? void 0 : _b2.call(_a2, instructionSet);
2938
+ instructionSet.add(this);
2939
+ };
2940
+ const collectChildren = () => {
2941
+ const children = this.children;
2942
+ const length = children.length;
2943
+ for (let i = 0; i < length; i++) {
2944
+ children[i].collectRenderables(instructionSet, renderer, currentLayer);
2945
+ }
2946
+ };
2947
+ const effects = this.effects;
2948
+ if (effects) {
2949
+ for (let i = 0; i < effects.length; i++) {
2950
+ const effect = effects[i];
2951
+ const filters = effect.filters;
2952
+ if (filters) {
2953
+ for (const f of filters) {
2954
+ if (f && typeof f.resolution === "number" && f.resolution === 1) {
2955
+ f.resolution = "inherit";
2956
+ }
2957
+ }
2958
+ }
2959
+ (_b = (_a = renderPipes[effect.pipe]) == null ? void 0 : _a.push) == null ? void 0 : _b.call(_a, effect, this, instructionSet);
2960
+ }
2961
+ addRenderable();
2962
+ collectChildren();
2963
+ for (let i = effects.length - 1; i >= 0; i--) {
2964
+ const effect = effects[i];
2965
+ (_d = (_c = renderPipes[effect.pipe]) == null ? void 0 : _c.pop) == null ? void 0 : _d.call(_c, effect, this, instructionSet);
2966
+ }
2967
+ } else {
2968
+ addRenderable();
2969
+ collectChildren();
2970
+ }
2971
+ }
2972
+ /**
2973
+ * A handler of the "modelLoaded" event, invoked when the internal model has been loaded.
2974
+ * @protected
2975
+ * @param _options - The options used for initialization.
2976
+ */
2977
+ initializeOnModelLoad(_options) {
2978
+ this.tag = `Live2DModel(${this.internalModel.settings.name})`;
2979
+ this.onAnchorChange();
2980
+ this.updateDrawableBounds();
2981
+ }
2982
+ /**
2983
+ * A callback that observes {@link anchor}, invoked when the anchor's values have been changed.
2984
+ * @protected
2985
+ */
2986
+ onAnchorChange() {
2987
+ if (!this.internalModel || !this.pivot) {
2988
+ return;
2989
+ }
2990
+ this.pivot.set(
2991
+ this.anchor.x * this.internalModel.width,
2992
+ this.anchor.y * this.internalModel.height
2993
+ );
2994
+ }
2995
+ /**
2996
+ * Shorthand to start a motion.
2997
+ * @param group - The motion group.
2998
+ * @param [index] - Index in the motion group.
2999
+ * @param [priority=2] - The priority to be applied. (0: No priority, 1: IDLE, 2:NORMAL, 3:FORCE)
3000
+ * @param {Object} options - Additional options for motion.
3001
+ * @param [options.sound] - The audio url to file or base64 content.
3002
+ * @param [options.volume=0.5] - Volume of the sound (0-1).
3003
+ * @param [options.expression] - In case you want to mix up an expression while playing sound (bind with Model.expression()).
3004
+ * @param [options.resetExpression=true] - Reset the expression to default after the motion is finished.
3005
+ * @param [options.onFinish] - Callback function when speaking completes.
3006
+ * @param [options.onError] - Callback function when an error occurs.
3007
+ * @return Promise that resolves with true if the motion is successfully started, with false otherwise.
3008
+ */
3009
+ motion(_0, _1, _2) {
3010
+ return __async(this, arguments, function* (group, index, priority, {
3011
+ sound: sound2 = void 0,
3012
+ volume = VOLUME,
3013
+ expression = void 0,
3014
+ resetExpression = true,
3015
+ onFinish,
3016
+ onError
3017
+ } = {}) {
3018
+ if (index === void 0) {
3019
+ return this.internalModel.motionManager.startRandomMotion(group, priority, {
3020
+ sound: sound2,
3021
+ volume,
3022
+ expression,
3023
+ resetExpression,
3024
+ onFinish,
3025
+ onError
3026
+ });
3027
+ } else {
3028
+ return this.internalModel.motionManager.startMotion(group, index, priority, {
3029
+ sound: sound2,
3030
+ volume,
3031
+ expression,
3032
+ resetExpression,
3033
+ onFinish,
3034
+ onError
3035
+ });
3036
+ }
3037
+ });
3038
+ }
3039
+ motionLastFrame(_0, _1) {
3040
+ return __async(this, arguments, function* (group, id, {
3041
+ expression = void 0
3042
+ } = {}) {
3043
+ return this.internalModel.motionManager.motionLastFrame(group, id, { expression });
3044
+ });
3045
+ }
3046
+ /**
3047
+ * Shorthand to start multiple motions in parallel.
3048
+ * @param motionList - The motion list, each item includes:
3049
+ * group: The motion group,
3050
+ * index: Index in the motion group,
3051
+ * priority: The priority to be applied. (0: No priority, 1: IDLE, 2:NORMAL, 3:FORCE) (default: 2)
3052
+ * @return Promise that resolves with a list, indicates the motion is successfully started, with false otherwise.
3053
+ */
3054
+ parallelMotion(motionList) {
3055
+ return __async(this, null, function* () {
3056
+ this.internalModel.extendParallelMotionManager(motionList.length);
3057
+ const result = motionList.map(
3058
+ (m, idx) => this.internalModel.parallelMotionManager[idx].startMotion(m.group, m.index, m.priority)
3059
+ );
3060
+ const flags = [];
3061
+ for (const r of result) {
3062
+ flags.push(yield r);
3063
+ }
3064
+ return flags;
3065
+ });
3066
+ }
3067
+ /**
3068
+ * Shorthand to play the last frame of multiple motions in parallel and await their completion.
3069
+ *
3070
+ * This method initiates the final frame of each specified motion concurrently,
3071
+ * leveraging the internal parallel motion manager. Each motion's completion is awaited
3072
+ * sequentially, and the results are returned as an array of success flags.
3073
+ *
3074
+ * @async
3075
+ * @param {{group: string, index: number, priority?: MotionPriority}[]} motionList - Array of motions to execute.
3076
+ * @param {string} motionList.group - Motion group identifier (e.g., "idle", "walk").
3077
+ * @param {number} motionList.index - Index within the motion group.
3078
+ * @param {MotionPriority} [motionList.priority=2] - Motion priority (0: None, 1: IDLE, 2: NORMAL, 3: FORCE).
3079
+ * @returns {Promise<boolean[]>} Resolves with an array where each boolean indicates
3080
+ * whether the corresponding motion completed successfully.
3081
+ */
3082
+ parallelLastFrame(motionList) {
3083
+ return __async(this, null, function* () {
3084
+ this.internalModel.extendParallelMotionManager(motionList.length);
3085
+ const result = motionList.map(
3086
+ (m, idx) => this.internalModel.parallelMotionManager[idx].playMotionLastFrame(m.group, m.index)
3087
+ );
3088
+ const flags = [];
3089
+ for (const r of result) {
3090
+ flags.push(yield r);
3091
+ }
3092
+ return flags;
3093
+ });
3094
+ }
3095
+ /**
3096
+ * Stops all playing motions as well as the sound.
3097
+ */
3098
+ stopMotions() {
3099
+ return this.internalModel.motionManager.stopAllMotions();
3100
+ }
3101
+ /**
3102
+ * Shorthand to start speaking a sound with an expression.
3103
+ * @param sound - The audio url to file or base64 content.
3104
+ * @param {Object} options - Additional options for speaking.
3105
+ * @param [options.volume] - Volume of the sound (0-1).
3106
+ * @param [options.expression] - In case you want to mix up an expression while playing sound (bind with Model.expression()).
3107
+ * @param [options.resetExpression=true] - Reset the expression to default after the motion is finished.
3108
+ * @param [options.onFinish] - Callback function when speaking completes.
3109
+ * @param [options.onError] - Callback function when an error occurs.
3110
+ * @returns Promise that resolves with true if the sound is playing, false if it's not.
3111
+ */
3112
+ speak(sound2, {
3113
+ volume = VOLUME,
3114
+ expression,
3115
+ resetExpression = true,
3116
+ onFinish,
3117
+ onError
3118
+ } = {}) {
3119
+ return this.internalModel.motionManager.speak(sound2, {
3120
+ volume,
3121
+ expression,
3122
+ resetExpression,
3123
+ onFinish,
3124
+ onError
3125
+ });
3126
+ }
3127
+ /**
3128
+ * Stop current audio playback and lipsync.
3129
+ */
3130
+ stopSpeaking() {
3131
+ return this.internalModel.motionManager.stopSpeaking();
3132
+ }
3133
+ /**
3134
+ * Shorthand to set an expression.
3135
+ * @param id - Either the index, or the name of the expression. If not presented, a random expression will be set.
3136
+ * @return Promise that resolves with true if succeeded, with false otherwise.
3137
+ */
3138
+ expression(id) {
3139
+ if (this.internalModel.motionManager.expressionManager) {
3140
+ return id === void 0 ? this.internalModel.motionManager.expressionManager.setRandomExpression() : this.internalModel.motionManager.expressionManager.setExpression(id);
3141
+ }
3142
+ return Promise.resolve(false);
3143
+ }
3144
+ /**
3145
+ * Updates the focus position. This will not cause the model to immediately look at the position,
3146
+ * instead the movement will be interpolated.
3147
+ * @param x - Position in world space.
3148
+ * @param y - Position in world space.
3149
+ * @param instant - Should the focus position be instantly applied.
3150
+ */
3151
+ focus(x, y, instant = false) {
3152
+ tempPoint.x = x;
3153
+ tempPoint.y = y;
3154
+ this.toModelPosition(tempPoint, tempPoint, true);
3155
+ const tx = tempPoint.x / this.internalModel.originalWidth * 2 - 1;
3156
+ const ty = tempPoint.y / this.internalModel.originalHeight * 2 - 1;
3157
+ const radian = Math.atan2(ty, tx);
3158
+ this.internalModel.focusController.focus(Math.cos(radian), -Math.sin(radian), instant);
3159
+ }
3160
+ /**
3161
+ * Tap on the model. This will perform a hit-testing, and emit a "hit" event
3162
+ * if at least one of the hit areas is hit.
3163
+ * @param x - Position in world space.
3164
+ * @param y - Position in world space.
3165
+ * @emits {@link Live2DModelEvents.hit}
3166
+ */
3167
+ tap(x, y) {
3168
+ const hitAreaNames = this.hitTest(x, y);
3169
+ if (hitAreaNames.length) {
3170
+ this.emit("hit", hitAreaNames);
3171
+ }
3172
+ }
3173
+ /**
3174
+ * Hit-test on the model.
3175
+ * @param x - Position in world space.
3176
+ * @param y - Position in world space.
3177
+ * @return The names of the *hit* hit areas. Can be empty if none is hit.
3178
+ */
3179
+ hitTest(x, y) {
3180
+ tempPoint.x = x;
3181
+ tempPoint.y = y;
3182
+ this.toModelPosition(tempPoint, tempPoint);
3183
+ return this.internalModel.hitTest(tempPoint.x, tempPoint.y);
3184
+ }
3185
+ /**
3186
+ * Calculates the position in the canvas of original, unscaled Live2D model.
3187
+ * @param position - A Point in world space.
3188
+ * @param result - A Point to store the new value. Defaults to a new Point.
3189
+ * @param skipUpdate - True to skip the update transform.
3190
+ * @return The Point in model canvas space.
3191
+ */
3192
+ toModelPosition(position, result = position.clone(), skipUpdate) {
3193
+ if (!skipUpdate) {
3194
+ this.updateLocalTransform();
3195
+ }
3196
+ this.toLocal(position, void 0, result, skipUpdate);
3197
+ this.internalModel.localTransform.applyInverse(result, result);
3198
+ return result;
3199
+ }
3200
+ /**
3201
+ * A method required by `PIXI.InteractionManager` to perform hit-testing.
3202
+ * @param point - A Point in local space.
3203
+ * @return True if the point is inside this model.
3204
+ */
3205
+ containsPoint(point) {
3206
+ return this.bounds.containsPoint(point.x, point.y);
3207
+ }
3208
+ /** @override
3209
+ * Calculates the bounds of the Live2DModel for rendering and interaction purposes.
3210
+ */
3211
+ _calculateBounds() {
3212
+ if (!this.internalModel) {
3213
+ this.getBounds().set(0, 0, 0, 0);
3214
+ return;
3215
+ }
3216
+ const width = this.internalModel.width;
3217
+ const height = this.internalModel.height;
3218
+ this.getBounds().addFrame(0, 0, width, height, this.transform.matrix);
3219
+ }
3220
+ /**
3221
+ * Updates the model. Note this method just updates the timer,
3222
+ * and the actual update will be done right before rendering the model.
3223
+ * @param dt - The elapsed time in milliseconds since last frame.
3224
+ */
3225
+ update(dt) {
3226
+ this.deltaTime += dt;
3227
+ this.elapsedTime += dt;
3228
+ }
3229
+ /**
3230
+ * Destroys the model and all related resources. This takes the same options and also
3231
+ * behaves the same as `PIXI.Container#destroy`.
3232
+ * @param options - Options parameter. A boolean will act as if all options
3233
+ * have been set to that value
3234
+ * @param [options.children=false] - if set to true, all the children will have their destroy
3235
+ * method called as well. `options` will be passed on to those calls.
3236
+ * @param [options.texture=false] - Only used for child Sprites if `options.children` is set to true
3237
+ * Should it destroy the texture of the child sprite
3238
+ * @param [options.baseTexture=false] - Only used for child Sprites if `options.children` is set to true
3239
+ * Should it destroy the base texture of the child sprite
3240
+ */
3241
+ destroy(options) {
3242
+ this.emit("destroy");
3243
+ if (options == null ? void 0 : options.texture) {
3244
+ this.textures.forEach((texture) => texture.destroy(options.baseTexture));
3245
+ }
3246
+ this.automator.destroy();
3247
+ this.internalModel.destroy();
3248
+ super.destroy(options);
3249
+ }
3250
+ }
3251
+ if (!("Live2D" in window)) {
3252
+ throw new Error(
3253
+ "Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded."
3254
+ );
3255
+ }
3256
+ const originalUpdateParam = Live2DMotion.prototype.updateParam;
3257
+ Live2DMotion.prototype.updateParam = function(model, entry) {
3258
+ originalUpdateParam.call(this, model, entry);
3259
+ if (entry.isFinished() && this.onFinishHandler) {
3260
+ this.onFinishHandler(this);
3261
+ delete this.onFinishHandler;
3262
+ }
3263
+ };
3264
+ class Live2DExpression extends AMotion {
3265
+ constructor(json) {
3266
+ super();
3267
+ __publicField(this, "params", []);
3268
+ this.setFadeIn(json.fade_in > 0 ? json.fade_in : config.expressionFadingDuration);
3269
+ this.setFadeOut(json.fade_out > 0 ? json.fade_out : config.expressionFadingDuration);
3270
+ if (Array.isArray(json.params)) {
3271
+ json.params.forEach((param) => {
3272
+ const calc = param.calc || "add";
3273
+ if (calc === "add") {
3274
+ const defaultValue = param.def || 0;
3275
+ param.val -= defaultValue;
3276
+ } else if (calc === "mult") {
3277
+ const defaultValue = param.def || 1;
3278
+ param.val /= defaultValue;
3279
+ }
3280
+ this.params.push({
3281
+ calc,
3282
+ val: param.val,
3283
+ id: param.id
3284
+ });
3285
+ });
3286
+ }
3287
+ }
3288
+ /** @override */
3289
+ updateParamExe(model, time, weight, _motionQueueEnt) {
3290
+ this.params.forEach((param) => {
3291
+ model.setParamFloat(param.id, param.val * weight);
3292
+ });
3293
+ }
3294
+ }
3295
+ class CubismLegacyExpressionManager extends ExpressionManager {
3296
+ constructor(settings, options) {
3297
+ var _a;
3298
+ super(settings, options);
3299
+ __publicField(this, "queueManager", new MotionQueueManager());
3300
+ __publicField(this, "definitions");
3301
+ this.definitions = (_a = this.settings.expressions) != null ? _a : [];
3302
+ this.init();
3303
+ }
3304
+ isFinished() {
3305
+ return this.queueManager.isFinished();
3306
+ }
3307
+ getExpressionIndex(name) {
3308
+ return this.definitions.findIndex((def) => def.name === name);
3309
+ }
3310
+ getExpressionFile(definition) {
3311
+ return definition.file;
3312
+ }
3313
+ createExpression(data, _definition) {
3314
+ return new Live2DExpression(data);
3315
+ }
3316
+ _setExpression(motion) {
3317
+ return this.queueManager.startMotion(motion);
3318
+ }
3319
+ stopAllExpressions() {
3320
+ this.queueManager.stopAllMotions();
3321
+ }
3322
+ updateParameters(model, _dt) {
3323
+ return this.queueManager.updateParam(model);
3324
+ }
3325
+ }
3326
+ function motionSkipToLastFrame(queueManager, internalModel, motion) {
3327
+ const duration = motion.getDurationMSec();
3328
+ const motionQueueEntNo = queueManager.startMotion(motion, true);
3329
+ const motionQueueEnt = queueManager.motions.find(
3330
+ (entry) => !!entry && entry._$sr === motionQueueEntNo
3331
+ );
3332
+ if (!motionQueueEnt) {
3333
+ return false;
3334
+ }
3335
+ motion.updateParamExe(internalModel.coreModel, duration, 1, motionQueueEnt);
3336
+ return true;
3337
+ }
3338
+ class CubismLegacyMotionManager extends MotionManager {
3339
+ constructor(parent) {
3340
+ super(parent);
3341
+ __publicField(this, "definitions");
3342
+ __publicField(this, "groups", { idle: "idle" });
3343
+ __publicField(this, "motionDataType", "arraybuffer");
3344
+ __publicField(this, "queueManager", new MotionQueueManager());
3345
+ __publicField(this, "lipSyncIds");
3346
+ __publicField(this, "expressionManager");
3347
+ this.definitions = this.settings.motions;
3348
+ this.init(parent.options);
3349
+ this.lipSyncIds = ["PARAM_MOUTH_OPEN_Y"];
3350
+ }
3351
+ init(options) {
3352
+ super.init(options);
3353
+ if (this.settings.expressions) {
3354
+ this.expressionManager = new CubismLegacyExpressionManager(this.settings, options);
3355
+ }
3356
+ }
3357
+ isFinished() {
3358
+ return this.queueManager.isFinished();
3359
+ }
3360
+ createMotion(data, group, definition) {
3361
+ const motion = Live2DMotion.loadMotion(data);
3362
+ const defaultFadingDuration = group === this.groups.idle ? config.idleMotionFadingDuration : config.motionFadingDuration;
3363
+ motion.setFadeIn(definition.fade_in > 0 ? definition.fade_in : defaultFadingDuration);
3364
+ motion.setFadeOut(definition.fade_out > 0 ? definition.fade_out : defaultFadingDuration);
3365
+ return motion;
3366
+ }
3367
+ getMotionFile(definition) {
3368
+ return definition.file;
3369
+ }
3370
+ getMotionName(definition) {
3371
+ return definition.file;
3372
+ }
3373
+ getSoundFile(definition) {
3374
+ return definition.sound;
3375
+ }
3376
+ _startMotion(motion, onFinish, ignoreParamIds) {
3377
+ motion.onFinishHandler = onFinish;
3378
+ if (ignoreParamIds && ignoreParamIds.length > 0) {
3379
+ motion.motions = motion.motions.filter((item) => {
3380
+ return !ignoreParamIds.includes(item._$4P);
3381
+ });
3382
+ }
3383
+ this.queueManager.stopAllMotions();
3384
+ return this.queueManager.startMotion(motion);
3385
+ }
3386
+ _stopAllMotions() {
3387
+ this.queueManager.stopAllMotions();
3388
+ }
3389
+ updateParameters(model, _now) {
3390
+ return this.queueManager.updateParam(model);
3391
+ }
3392
+ destroy() {
3393
+ super.destroy();
3394
+ this.queueManager = void 0;
3395
+ }
3396
+ motionLastFrame(_0, _1) {
3397
+ return __async(this, arguments, function* (group, index, {
3398
+ expression = void 0
3399
+ } = {}) {
3400
+ const motion = yield this.getMotionAndApplyExpression(group, index, expression);
3401
+ if (!motion) {
3402
+ return false;
3403
+ }
3404
+ this.playing = true;
3405
+ motionSkipToLastFrame(
3406
+ this.queueManager,
3407
+ this.parent,
3408
+ motion
3409
+ );
3410
+ this.playing = false;
3411
+ return true;
3412
+ });
3413
+ }
3414
+ }
3415
+ class ParallelMotionManager extends EventEmitter {
3416
+ constructor(parent) {
3417
+ super();
3418
+ /**
3419
+ * Tag for logging.
3420
+ */
3421
+ __publicField(this, "tag");
3422
+ __publicField(this, "manager");
3423
+ /**
3424
+ * The ModelSettings reference.
3425
+ */
3426
+ __publicField(this, "settings");
3427
+ /**
3428
+ * Maintains the state of this MotionManager.
3429
+ */
3430
+ __publicField(this, "state", new MotionState());
3431
+ /**
3432
+ * Flags there's a motion playing.
3433
+ */
3434
+ __publicField(this, "playing", false);
3435
+ /**
3436
+ * Flags the instances has been destroyed.
3437
+ */
3438
+ __publicField(this, "destroyed", false);
3439
+ __publicField(this, "parent");
3440
+ this.settings = parent.settings;
3441
+ this.tag = `ParallelMotionManager(${this.settings.name})`;
3442
+ this.state.tag = this.tag;
3443
+ this.manager = parent.motionManager;
3444
+ this.parent = parent;
3445
+ }
3446
+ /**
3447
+ * Starts a motion as given priority.
3448
+ * @param group - The motion group.
3449
+ * @param index - Index in the motion group.
3450
+ * @param priority - The priority to be applied. default: 2 (NORMAL)
3451
+ * @param ignoreParamIds - The ids to be ignored.
3452
+ * @return Promise that resolves with true if the motion is successfully started, with false otherwise.
3453
+ */
3454
+ startMotion(_0, _1) {
3455
+ return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, ignoreParamIds = []) {
3456
+ var _a;
3457
+ if (!this.state.reserve(group, index, priority)) {
3458
+ return false;
3459
+ }
3460
+ const definition = (_a = this.manager.definitions[group]) == null ? void 0 : _a[index];
3461
+ if (!definition) {
3462
+ return false;
3463
+ }
3464
+ const motion = yield this.manager.loadMotion(group, index);
3465
+ if (!this.state.start(motion, group, index, priority)) {
3466
+ return false;
3467
+ }
3468
+ logger.log(this.tag, "Start motion:", this.getMotionName(definition));
3469
+ this.emit("motionStart", group, index, void 0);
3470
+ this.playing = true;
3471
+ this._startMotion(motion, void 0, ignoreParamIds);
3472
+ return true;
3473
+ });
3474
+ }
3475
+ /**
3476
+ * Starts a random Motion as given priority.
3477
+ * @param group - The motion group.
3478
+ * @param priority - The priority to be applied. (default: 1 `IDLE`)
3479
+ * @return Promise that resolves with true if the motion is successfully started, with false otherwise.
3480
+ */
3481
+ startRandomMotion(group, priority) {
3482
+ return __async(this, null, function* () {
3483
+ var _a;
3484
+ const groupDefs = this.manager.definitions[group];
3485
+ if (groupDefs == null ? void 0 : groupDefs.length) {
3486
+ const availableIndices = [];
3487
+ const groupMotions = (_a = this.manager.motionGroups[group]) != null ? _a : [];
3488
+ for (let i = 0; i < groupDefs.length; i++) {
3489
+ if (groupMotions[i] !== null && !this.state.isActive(group, i)) {
3490
+ availableIndices.push(i);
3491
+ }
3492
+ }
3493
+ if (availableIndices.length) {
3494
+ const index = availableIndices[Math.floor(Math.random() * availableIndices.length)];
3495
+ return this.startMotion(group, index, priority);
3496
+ }
3497
+ }
3498
+ return false;
3499
+ });
3500
+ }
3501
+ /**
3502
+ * Stops all playing motions as well as the sound.
3503
+ */
3504
+ stopAllMotions() {
3505
+ this._stopAllMotions();
3506
+ this.state.reset();
3507
+ }
3508
+ /**
3509
+ * Updates parameters of the core model.
3510
+ * @param model - The core model.
3511
+ * @param now - Current time in milliseconds.
3512
+ * @return True if the parameters have been actually updated.
3513
+ */
3514
+ update(model, now) {
3515
+ if (this.isFinished()) {
3516
+ if (this.playing) {
3517
+ this.playing = false;
3518
+ this.emit("motionFinish");
3519
+ }
3520
+ this.state.complete();
3521
+ }
3522
+ return this.updateParameters(model, now);
3523
+ }
3524
+ /**
3525
+ * Destroys the instance.
3526
+ * @emits {@link MotionManagerEvents.destroy}
3527
+ */
3528
+ destroy() {
3529
+ this.destroyed = true;
3530
+ this.emit("destroy");
3531
+ this.stopAllMotions();
3532
+ }
3533
+ }
3534
+ class CubismLegacyParallelMotionManager extends ParallelMotionManager {
3535
+ constructor(parent) {
3536
+ super(parent);
3537
+ __publicField(this, "queueManager", new MotionQueueManager());
3538
+ }
3539
+ isFinished() {
3540
+ return this.queueManager.isFinished();
3541
+ }
3542
+ getMotionName(definition) {
3543
+ return definition.file;
3544
+ }
3545
+ _startMotion(motion, onFinish, ignoreParamIds) {
3546
+ motion.onFinishHandler = onFinish;
3547
+ if (ignoreParamIds && ignoreParamIds.length > 0) {
3548
+ motion.motions = motion.motions.filter((item) => {
3549
+ return !ignoreParamIds.includes(item._$4P);
3550
+ });
3551
+ }
3552
+ this.queueManager.stopAllMotions();
3553
+ return this.queueManager.startMotion(motion);
3554
+ }
3555
+ _stopAllMotions() {
3556
+ this.queueManager.stopAllMotions();
3557
+ }
3558
+ updateParameters(model, _now) {
3559
+ return this.queueManager.updateParam(model);
3560
+ }
3561
+ destroy() {
3562
+ super.destroy();
3563
+ this.queueManager = void 0;
3564
+ }
3565
+ playMotionLastFrame(group, index) {
3566
+ return __async(this, null, function* () {
3567
+ var _a;
3568
+ if (!this.state.reserve(group, index, MotionPriority.FORCE)) {
3569
+ return false;
3570
+ }
3571
+ const definition = (_a = this.manager.definitions[group]) == null ? void 0 : _a[index];
3572
+ if (!definition) {
3573
+ return false;
3574
+ }
3575
+ const motion = yield this.manager.loadMotion(group, index);
3576
+ if (!this.state.start(motion, group, index, MotionPriority.FORCE)) {
3577
+ return false;
3578
+ }
3579
+ logger.log(this.tag, "Start motion:", this.getMotionName(definition));
3580
+ this.queueManager.stopAllMotions();
3581
+ this.emit("motionStart", group, index, void 0);
3582
+ this.playing = true;
3583
+ if (!motionSkipToLastFrame(this.queueManager, this.parent, motion)) {
3584
+ return false;
3585
+ }
3586
+ this.playing = false;
3587
+ return true;
3588
+ });
3589
+ }
3590
+ }
3591
+ class Live2DEyeBlink {
3592
+ constructor(coreModel) {
3593
+ __publicField(this, "leftParam");
3594
+ __publicField(this, "rightParam");
3595
+ __publicField(this, "blinkInterval", 4e3);
3596
+ __publicField(this, "closingDuration", 100);
3597
+ __publicField(this, "closedDuration", 50);
3598
+ __publicField(this, "openingDuration", 150);
3599
+ __publicField(this, "eyeState", 0);
3600
+ __publicField(this, "eyeParamValue", 1);
3601
+ __publicField(this, "closedTimer", 0);
3602
+ __publicField(this, "nextBlinkTimeLeft", this.blinkInterval);
3603
+ this.coreModel = coreModel;
3604
+ this.leftParam = coreModel.getParamIndex("PARAM_EYE_L_OPEN");
3605
+ this.rightParam = coreModel.getParamIndex("PARAM_EYE_R_OPEN");
3606
+ }
3607
+ setEyeParams(value) {
3608
+ this.eyeParamValue = clamp(value, 0, 1);
3609
+ this.coreModel.setParamFloat(this.leftParam, this.eyeParamValue);
3610
+ this.coreModel.setParamFloat(this.rightParam, this.eyeParamValue);
3611
+ }
3612
+ update(dt) {
3613
+ switch (this.eyeState) {
3614
+ case 0:
3615
+ this.nextBlinkTimeLeft -= dt;
3616
+ if (this.nextBlinkTimeLeft < 0) {
3617
+ this.eyeState = 1;
3618
+ this.nextBlinkTimeLeft = this.blinkInterval + this.closingDuration + this.closedDuration + this.openingDuration + rand(0, 2e3);
3619
+ }
3620
+ break;
3621
+ case 1:
3622
+ this.setEyeParams(this.eyeParamValue + dt / this.closingDuration);
3623
+ if (this.eyeParamValue <= 0) {
3624
+ this.eyeState = 2;
3625
+ this.closedTimer = 0;
3626
+ }
3627
+ break;
3628
+ case 2:
3629
+ this.closedTimer += dt;
3630
+ if (this.closedTimer >= this.closedDuration) {
3631
+ this.eyeState = 3;
3632
+ }
3633
+ break;
3634
+ case 3:
3635
+ this.setEyeParams(this.eyeParamValue + dt / this.openingDuration);
3636
+ if (this.eyeParamValue >= 1) {
3637
+ this.eyeState = 0;
3638
+ }
3639
+ }
3640
+ }
3641
+ }
3642
+ const tempMatrixArray = new Float32Array([
3643
+ 1,
3644
+ 0,
3645
+ 0,
3646
+ 0,
3647
+ 0,
3648
+ 1,
3649
+ 0,
3650
+ 0,
3651
+ 0,
3652
+ 0,
3653
+ 1,
3654
+ 0,
3655
+ 0,
3656
+ 0,
3657
+ 0,
3658
+ 1
3659
+ ]);
3660
+ class CubismLegacyInternalModel extends InternalModel {
3661
+ constructor(coreModel, settings, options) {
3662
+ super();
3663
+ __publicField(this, "settings");
3664
+ __publicField(this, "options");
3665
+ __publicField(this, "coreModel");
3666
+ __publicField(this, "motionManager");
3667
+ __publicField(this, "parallelMotionManager");
3668
+ __publicField(this, "eyeBlink");
3669
+ // parameter indices, cached for better performance
3670
+ __publicField(this, "eyeballXParamIndex");
3671
+ __publicField(this, "eyeballYParamIndex");
3672
+ __publicField(this, "angleXParamIndex");
3673
+ __publicField(this, "angleYParamIndex");
3674
+ __publicField(this, "angleZParamIndex");
3675
+ __publicField(this, "bodyAngleXParamIndex");
3676
+ __publicField(this, "breathParamIndex");
3677
+ // mouthFormIndex: number;
3678
+ __publicField(this, "textureFlipY", true);
3679
+ __publicField(this, "lipSync", true);
3680
+ /**
3681
+ * Number of the drawables in this model.
3682
+ */
3683
+ __publicField(this, "drawDataCount", 0);
3684
+ /**
3685
+ * If true, the face culling will always be disabled when drawing the model,
3686
+ * regardless of the model's internal flags.
3687
+ */
3688
+ __publicField(this, "disableCulling", false);
3689
+ __publicField(this, "hasDrawn", false);
3690
+ __publicField(this, "customHitAreas");
3691
+ this.coreModel = coreModel;
3692
+ this.settings = settings;
3693
+ this.options = Object.assign({}, { breathDepth: 1 }, options);
3694
+ this.motionManager = new CubismLegacyMotionManager(this);
3695
+ this.parallelMotionManager = [];
3696
+ this.eyeBlink = new Live2DEyeBlink(coreModel);
3697
+ this.eyeballXParamIndex = coreModel.getParamIndex("PARAM_EYE_BALL_X");
3698
+ this.eyeballYParamIndex = coreModel.getParamIndex("PARAM_EYE_BALL_Y");
3699
+ this.angleXParamIndex = coreModel.getParamIndex("PARAM_ANGLE_X");
3700
+ this.angleYParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Y");
3701
+ this.angleZParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Z");
3702
+ this.bodyAngleXParamIndex = coreModel.getParamIndex("PARAM_BODY_ANGLE_X");
3703
+ this.breathParamIndex = coreModel.getParamIndex("PARAM_BREATH");
3704
+ this.init();
3705
+ }
3706
+ init() {
3707
+ super.init();
3708
+ if (this.settings.initParams) {
3709
+ this.settings.initParams.forEach(({ id, value }) => this.coreModel.setParamFloat(id, value));
3710
+ }
3711
+ if (this.settings.initOpacities) {
3712
+ this.settings.initOpacities.forEach(
3713
+ ({ id, value }) => this.coreModel.setPartsOpacity(id, value)
3714
+ );
3715
+ }
3716
+ this.coreModel.saveParam();
3717
+ const arr = this.coreModel.getModelContext()._$aS;
3718
+ if (arr == null ? void 0 : arr.length) {
3719
+ this.drawDataCount = arr.length;
3720
+ }
3721
+ let culling = this.coreModel.drawParamWebGL.culling;
3722
+ Object.defineProperty(this.coreModel.drawParamWebGL, "culling", {
3723
+ set: (v) => culling = v,
3724
+ // always return false when disabled
3725
+ get: () => this.disableCulling ? false : culling
3726
+ });
3727
+ const clipManager = this.coreModel.getModelContext().clipManager;
3728
+ const originalSetupClip = clipManager.setupClip.bind(clipManager);
3729
+ clipManager.setupClip = (modelContext, drawParam) => {
3730
+ originalSetupClip.call(clipManager, modelContext, drawParam);
3731
+ drawParam.gl.viewport(...this.viewport);
3732
+ };
3733
+ }
3734
+ getSize() {
3735
+ return [this.coreModel.getCanvasWidth(), this.coreModel.getCanvasHeight()];
3736
+ }
3737
+ getLayout() {
3738
+ const layout = {};
3739
+ if (this.settings.layout) {
3740
+ for (const [key, value] of Object.entries(this.settings.layout)) {
3741
+ let commonKey = key;
3742
+ if (key === "center_x") {
3743
+ commonKey = "centerX";
3744
+ } else if (key === "center_y") {
3745
+ commonKey = "centerY";
3746
+ }
3747
+ if (typeof value === "number") {
3748
+ layout[commonKey] = value;
3749
+ }
3750
+ }
3751
+ }
3752
+ return layout;
3753
+ }
3754
+ updateWebGLContext(gl, glContextID) {
3755
+ const drawParamWebGL = this.coreModel.drawParamWebGL;
3756
+ drawParamWebGL.firstDraw = true;
3757
+ drawParamWebGL.setGL(gl);
3758
+ drawParamWebGL.glno = glContextID;
3759
+ drawParamWebGL._$NT = null;
3760
+ drawParamWebGL._$no = null;
3761
+ drawParamWebGL._$vS = null;
3762
+ const clipManager = this.coreModel.getModelContext().clipManager;
3763
+ clipManager.curFrameNo = glContextID;
3764
+ const framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
3765
+ clipManager.getMaskRenderTexture();
3766
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
3767
+ }
3768
+ bindTexture(index, texture) {
3769
+ this.coreModel.setTexture(index, texture);
3770
+ }
3771
+ getHitAreaDefs() {
3772
+ var _a, _b, _c;
3773
+ const json = this.settings.json;
3774
+ const rawHitAreas = (_c = (_b = (_a = this.settings.hitAreas) != null ? _a : json.hit_areas) != null ? _b : json.HitAreas) != null ? _c : json.hitAreas;
3775
+ return normalizeHitAreaDefs(rawHitAreas, (id) => this.coreModel.getDrawDataIndex(id));
3776
+ }
3777
+ getDrawableIDs() {
3778
+ const modelContext = this.coreModel.getModelContext();
3779
+ const ids = [];
3780
+ for (let i = 0; i < this.drawDataCount; i++) {
3781
+ const drawData = modelContext.getDrawData(i);
3782
+ if (drawData) {
3783
+ ids.push(drawData.getDrawDataID().id);
3784
+ }
3785
+ }
3786
+ return ids;
3787
+ }
3788
+ getDrawableIndex(id) {
3789
+ return this.coreModel.getDrawDataIndex(id);
3790
+ }
3791
+ getDrawableVertices(drawIndex) {
3792
+ if (typeof drawIndex === "string") {
3793
+ drawIndex = this.coreModel.getDrawDataIndex(drawIndex);
3794
+ if (drawIndex === -1) throw new TypeError("Unable to find drawable ID: " + drawIndex);
3795
+ }
3796
+ return this.coreModel.getTransformedPoints(drawIndex).slice();
3797
+ }
3798
+ hitTest(x, y) {
3799
+ if (!this.hasDrawn) {
3800
+ logger.warn(
3801
+ "Trying to hit-test a Cubism 2 model that has not been rendered yet. Drawable hit areas may be empty until the first draw."
3802
+ );
3803
+ }
3804
+ const drawableHits = super.hitTest(x, y);
3805
+ const customHits = this.hitTestCustom(x, y);
3806
+ if (!customHits.length) {
3807
+ return drawableHits;
3808
+ }
3809
+ if (!drawableHits.length) {
3810
+ return customHits;
3811
+ }
3812
+ return [.../* @__PURE__ */ new Set([...drawableHits, ...customHits])];
3813
+ }
3814
+ update(dt, now) {
3815
+ var _a, _b, _c, _d;
3816
+ super.update(dt, now);
3817
+ const model = this.coreModel;
3818
+ const motionUpdated = this.updateMotions(model, now);
3819
+ model.saveParam();
3820
+ (_a = this.motionManager.expressionManager) == null ? void 0 : _a.update(model, now);
3821
+ if (!motionUpdated) {
3822
+ (_b = this.eyeBlink) == null ? void 0 : _b.update(dt);
3823
+ }
3824
+ this.updateFocus();
3825
+ this.updateNaturalMovements(dt, now);
3826
+ if (this.lipSync && this.motionManager.currentAudio) {
3827
+ const lipSyncGain = 1.5;
3828
+ let value = this.motionManager.mouthSync() * lipSyncGain;
3829
+ const max_ = 1;
3830
+ const bias_power = 1.15;
3831
+ const min_ = value > 0 ? 0.1 : 0;
3832
+ value = Math.pow(value, bias_power);
3833
+ value = clamp(value, min_, max_);
3834
+ for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) {
3835
+ this.coreModel.setParamFloat(
3836
+ this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]),
3837
+ value
3838
+ );
3839
+ }
3840
+ }
3841
+ (_c = this.physics) == null ? void 0 : _c.update(now);
3842
+ (_d = this.pose) == null ? void 0 : _d.update(dt);
3843
+ this.emit("beforeModelUpdate");
3844
+ model.update();
3845
+ model.loadParam();
3846
+ }
3847
+ updateFocus() {
3848
+ this.coreModel.addToParamFloat(this.eyeballXParamIndex, this.focusController.x);
3849
+ this.coreModel.addToParamFloat(this.eyeballYParamIndex, this.focusController.y);
3850
+ this.coreModel.addToParamFloat(this.angleXParamIndex, this.focusController.x * 30);
3851
+ this.coreModel.addToParamFloat(this.angleYParamIndex, this.focusController.y * 30);
3852
+ this.coreModel.addToParamFloat(
3853
+ this.angleZParamIndex,
3854
+ this.focusController.x * this.focusController.y * -30
3855
+ );
3856
+ this.coreModel.addToParamFloat(this.bodyAngleXParamIndex, this.focusController.x * 10);
3857
+ }
3858
+ updateNaturalMovements(_dt, now) {
3859
+ const t = now / 1e3 * 2 * Math.PI;
3860
+ this.coreModel.addToParamFloat(
3861
+ this.angleXParamIndex,
3862
+ 15 * this.options.breathDepth * Math.sin(t / 6.5345) * 0.5
3863
+ );
3864
+ this.coreModel.addToParamFloat(
3865
+ this.angleYParamIndex,
3866
+ 8 * this.options.breathDepth * Math.sin(t / 3.5345) * 0.5
3867
+ );
3868
+ this.coreModel.addToParamFloat(
3869
+ this.angleZParamIndex,
3870
+ 10 * this.options.breathDepth * Math.sin(t / 5.5345) * 0.5
3871
+ );
3872
+ this.coreModel.addToParamFloat(
3873
+ this.bodyAngleXParamIndex,
3874
+ 4 * this.options.breathDepth * Math.sin(t / 15.5345) * 0.5
3875
+ );
3876
+ this.coreModel.setParamFloat(this.breathParamIndex, 0.5 + 0.5 * Math.sin(t / 3.2345));
3877
+ }
3878
+ draw(gl) {
3879
+ const disableCulling = this.disableCulling;
3880
+ if (gl.getParameter(gl.FRAMEBUFFER_BINDING)) {
3881
+ this.disableCulling = true;
3882
+ }
3883
+ const matrix = this.drawingMatrix;
3884
+ tempMatrixArray[0] = matrix.a;
3885
+ tempMatrixArray[1] = matrix.b;
3886
+ tempMatrixArray[4] = matrix.c;
3887
+ tempMatrixArray[5] = matrix.d;
3888
+ tempMatrixArray[12] = matrix.tx;
3889
+ tempMatrixArray[13] = matrix.ty;
3890
+ this.coreModel.setMatrix(tempMatrixArray);
3891
+ this.coreModel.draw();
3892
+ this.hasDrawn = true;
3893
+ this.disableCulling = disableCulling;
3894
+ }
3895
+ extendParallelMotionManager(managerCount) {
3896
+ while (this.parallelMotionManager.length < managerCount) {
3897
+ this.parallelMotionManager.push(new CubismLegacyParallelMotionManager(this));
3898
+ }
3899
+ }
3900
+ destroy() {
3901
+ super.destroy();
3902
+ this.coreModel = void 0;
3903
+ }
3904
+ hitTestCustom(x, y) {
3905
+ const areas = this.getCustomHitAreas();
3906
+ if (!areas) {
3907
+ return [];
3908
+ }
3909
+ const width = this.originalWidth || this.width;
3910
+ const height = this.originalHeight || this.height;
3911
+ if (!width || !height) {
3912
+ return [];
3913
+ }
3914
+ const logicalX = x / width * LOGICAL_WIDTH - LOGICAL_WIDTH / 2;
3915
+ const logicalY = LOGICAL_HEIGHT / 2 - y / height * LOGICAL_HEIGHT;
3916
+ const hits = [];
3917
+ for (const [name, area] of Object.entries(areas)) {
3918
+ if (logicalX >= area.minX && logicalX <= area.maxX && logicalY >= area.minY && logicalY <= area.maxY) {
3919
+ hits.push(name);
3920
+ }
3921
+ }
3922
+ return hits;
3923
+ }
3924
+ getCustomHitAreas() {
3925
+ var _a, _b, _c, _d, _e;
3926
+ if (this.customHitAreas !== void 0) {
3927
+ return this.customHitAreas;
3928
+ }
3929
+ const json = this.settings.json;
3930
+ const raw = (_c = (_b = (_a = json.hit_areas_custom) != null ? _a : json.hitAreasCustom) != null ? _b : json.HitAreasCustom) != null ? _c : json.HitAreas_Custom;
3931
+ if (!raw || typeof raw !== "object") {
3932
+ this.customHitAreas = null;
3933
+ return null;
3934
+ }
3935
+ const rawRecord = raw;
3936
+ const areas = {};
3937
+ const addArea = (name, xRange, yRange) => {
3938
+ if (!name || !Array.isArray(xRange) || !Array.isArray(yRange)) {
3939
+ return;
3940
+ }
3941
+ if (xRange.length < 2 || yRange.length < 2) {
3942
+ return;
3943
+ }
3944
+ const x0 = Number(xRange[0]);
3945
+ const x1 = Number(xRange[1]);
3946
+ const y0 = Number(yRange[0]);
3947
+ const y1 = Number(yRange[1]);
3948
+ if (!Number.isFinite(x0) || !Number.isFinite(x1) || !Number.isFinite(y0) || !Number.isFinite(y1)) {
3949
+ return;
3950
+ }
3951
+ areas[name] = {
3952
+ minX: Math.min(x0, x1),
3953
+ maxX: Math.max(x0, x1),
3954
+ minY: Math.min(y0, y1),
3955
+ maxY: Math.max(y0, y1)
3956
+ };
3957
+ };
3958
+ for (const [key, value] of Object.entries(rawRecord)) {
3959
+ if (key.endsWith("_x")) {
3960
+ const name = key.slice(0, -2);
3961
+ addArea(name, value, rawRecord[`${name}_y`]);
3962
+ continue;
3963
+ }
3964
+ if (key.endsWith("_y")) {
3965
+ continue;
3966
+ }
3967
+ if (value && typeof value === "object") {
3968
+ const record = value;
3969
+ const xRange = (_d = record.x) != null ? _d : record.X;
3970
+ const yRange = (_e = record.y) != null ? _e : record.Y;
3971
+ addArea(key, xRange, yRange);
3972
+ }
3973
+ }
3974
+ this.customHitAreas = Object.keys(areas).length ? areas : null;
3975
+ return this.customHitAreas;
3976
+ }
3977
+ }
3978
+ const SRC_TYPE_MAP = {
3979
+ x: PhysicsHair.Src.SRC_TO_X,
3980
+ y: PhysicsHair.Src.SRC_TO_Y,
3981
+ angle: PhysicsHair.Src.SRC_TO_G_ANGLE
3982
+ };
3983
+ const TARGET_TYPE_MAP = {
3984
+ x: PhysicsHair.Src.SRC_TO_X,
3985
+ y: PhysicsHair.Src.SRC_TO_Y,
3986
+ angle: PhysicsHair.Src.SRC_TO_G_ANGLE
3987
+ };
3988
+ class Live2DPhysics {
3989
+ constructor(coreModel, json) {
3990
+ __publicField(this, "physicsHairs", []);
3991
+ this.coreModel = coreModel;
3992
+ if (json.physics_hair) {
3993
+ this.physicsHairs = json.physics_hair.map((definition) => {
3994
+ const physicsHair = new PhysicsHair();
3995
+ physicsHair.setup(definition.setup.length, definition.setup.regist, definition.setup.mass);
3996
+ definition.src.forEach(({ id, ptype, scale, weight }) => {
3997
+ const type = SRC_TYPE_MAP[ptype];
3998
+ if (type) {
3999
+ physicsHair.addSrcParam(type, id, scale, weight);
4000
+ }
4001
+ });
4002
+ definition.targets.forEach(({ id, ptype, scale, weight }) => {
4003
+ const type = TARGET_TYPE_MAP[ptype];
4004
+ if (type) {
4005
+ physicsHair.addTargetParam(type, id, scale, weight);
4006
+ }
4007
+ });
4008
+ return physicsHair;
4009
+ });
4010
+ }
4011
+ }
4012
+ update(elapsed) {
4013
+ this.physicsHairs.forEach((physicsHair) => physicsHair.update(this.coreModel, elapsed));
4014
+ }
4015
+ }
4016
+ class Live2DPartsParam {
4017
+ constructor(id) {
4018
+ __publicField(this, "paramIndex", -1);
4019
+ __publicField(this, "partsIndex", -1);
4020
+ __publicField(this, "link", []);
4021
+ this.id = id;
4022
+ }
4023
+ initIndex(model) {
4024
+ this.paramIndex = model.getParamIndex("VISIBLE:" + this.id);
4025
+ this.partsIndex = model.getPartsDataIndex(PartsDataID.getID(this.id));
4026
+ model.setParamFloat(this.paramIndex, 1);
4027
+ }
4028
+ }
4029
+ class Live2DPose {
4030
+ constructor(coreModel, json) {
4031
+ __publicField(this, "opacityAnimDuration", 500);
4032
+ __publicField(this, "partsGroups", []);
4033
+ this.coreModel = coreModel;
4034
+ if (json.parts_visible) {
4035
+ this.partsGroups = json.parts_visible.map(
4036
+ ({ group }) => group.map(({ id, link }) => {
4037
+ const parts = new Live2DPartsParam(id);
4038
+ if (link) {
4039
+ parts.link = link.map((l) => new Live2DPartsParam(l));
4040
+ }
4041
+ return parts;
4042
+ })
4043
+ );
4044
+ this.init();
4045
+ }
4046
+ }
4047
+ init() {
4048
+ this.partsGroups.forEach((group) => {
4049
+ group.forEach((parts) => {
4050
+ parts.initIndex(this.coreModel);
4051
+ if (parts.paramIndex >= 0) {
4052
+ const visible = this.coreModel.getParamFloat(parts.paramIndex) !== 0;
4053
+ this.coreModel.setPartsOpacity(parts.partsIndex, visible ? 1 : 0);
4054
+ this.coreModel.setParamFloat(parts.paramIndex, visible ? 1 : 0);
4055
+ if (parts.link.length > 0) {
4056
+ parts.link.forEach((p) => p.initIndex(this.coreModel));
4057
+ }
4058
+ }
4059
+ });
4060
+ });
4061
+ }
4062
+ normalizePartsOpacityGroup(partsGroup, dt) {
4063
+ const model = this.coreModel;
4064
+ const phi = 0.5;
4065
+ const maxBackOpacity = 0.15;
4066
+ let visibleOpacity = 1;
4067
+ let visibleIndex = partsGroup.findIndex(
4068
+ ({ paramIndex, partsIndex }) => partsIndex >= 0 && model.getParamFloat(paramIndex) !== 0
4069
+ );
4070
+ if (visibleIndex >= 0) {
4071
+ const originalOpacity = model.getPartsOpacity(partsGroup[visibleIndex].partsIndex);
4072
+ visibleOpacity = clamp(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
4073
+ } else {
4074
+ visibleIndex = 0;
4075
+ visibleOpacity = 1;
4076
+ }
4077
+ partsGroup.forEach(({ partsIndex }, index) => {
4078
+ if (partsIndex >= 0) {
4079
+ if (visibleIndex == index) {
4080
+ model.setPartsOpacity(partsIndex, visibleOpacity);
4081
+ } else {
4082
+ let opacity = model.getPartsOpacity(partsIndex);
4083
+ let a1;
4084
+ if (visibleOpacity < phi) {
4085
+ a1 = visibleOpacity * (phi - 1) / phi + 1;
4086
+ } else {
4087
+ a1 = (1 - visibleOpacity) * phi / (1 - phi);
4088
+ }
4089
+ const backOp = (1 - a1) * (1 - visibleOpacity);
4090
+ if (backOp > maxBackOpacity) {
4091
+ a1 = 1 - maxBackOpacity / (1 - visibleOpacity);
4092
+ }
4093
+ if (opacity > a1) {
4094
+ opacity = a1;
4095
+ }
4096
+ model.setPartsOpacity(partsIndex, opacity);
4097
+ }
4098
+ }
4099
+ });
4100
+ }
4101
+ copyOpacity(partsGroup) {
4102
+ const model = this.coreModel;
4103
+ partsGroup.forEach(({ partsIndex, link }) => {
4104
+ if (partsIndex >= 0 && link) {
4105
+ const opacity = model.getPartsOpacity(partsIndex);
4106
+ link.forEach(({ partsIndex: partsIndex2 }) => {
4107
+ if (partsIndex2 >= 0) {
4108
+ model.setPartsOpacity(partsIndex2, opacity);
4109
+ }
4110
+ });
4111
+ }
4112
+ });
4113
+ }
4114
+ update(dt) {
4115
+ this.partsGroups.forEach((partGroup) => {
4116
+ this.normalizePartsOpacityGroup(partGroup, dt);
4117
+ this.copyOpacity(partGroup);
4118
+ });
4119
+ }
4120
+ }
4121
+ Live2DFactory.registerRuntime({
4122
+ version: 2,
4123
+ test(source) {
4124
+ return source instanceof CubismLegacyModelSettings || CubismLegacyModelSettings.isValidJSON(source);
4125
+ },
4126
+ ready() {
4127
+ return Promise.resolve();
4128
+ },
4129
+ isValidMoc(modelData) {
4130
+ if (modelData.byteLength < 3) {
4131
+ return false;
4132
+ }
4133
+ const view = new Int8Array(modelData, 0, 3);
4134
+ return String.fromCharCode(...view) === "moc";
4135
+ },
4136
+ createModelSettings(json) {
4137
+ return new CubismLegacyModelSettings(json);
4138
+ },
4139
+ createCoreModel(data) {
4140
+ const model = Live2DModelWebGL.loadModel(data);
4141
+ const error = Live2D.getError();
4142
+ if (error) {
4143
+ if (error instanceof Error) {
4144
+ throw error;
4145
+ }
4146
+ const message = typeof error === "string" ? error : `Live2D error: ${JSON.stringify(error)}`;
4147
+ throw new Error(message);
4148
+ }
4149
+ return model;
4150
+ },
4151
+ createInternalModel(coreModel, settings, options) {
4152
+ return new CubismLegacyInternalModel(coreModel, settings, options);
4153
+ },
4154
+ createPose(coreModel, data) {
4155
+ return new Live2DPose(coreModel, data);
4156
+ },
4157
+ createPhysics(coreModel, data) {
4158
+ return new Live2DPhysics(coreModel, data);
4159
+ }
4160
+ });
4161
+ export {
4162
+ CubismLegacyExpressionManager,
4163
+ CubismLegacyInternalModel,
4164
+ CubismLegacyModelSettings,
4165
+ CubismLegacyMotionManager,
4166
+ CubismLegacyParallelMotionManager,
4167
+ ExpressionManager,
4168
+ FileLoader,
4169
+ FocusController,
4170
+ InternalModel,
4171
+ LOGICAL_HEIGHT,
4172
+ LOGICAL_WIDTH,
4173
+ Live2DExpression,
4174
+ Live2DEyeBlink,
4175
+ Live2DFactory,
4176
+ Live2DLoader,
4177
+ Live2DModel,
4178
+ Live2DPhysics,
4179
+ Live2DPose,
4180
+ Live2DTransform,
4181
+ MBToByte,
4182
+ ModelSettings,
4183
+ MotionManager,
4184
+ MotionPreloadStrategy,
4185
+ MotionPriority,
4186
+ MotionState,
4187
+ SoundManager,
4188
+ VERSION,
4189
+ VOLUME,
4190
+ XHRLoader,
4191
+ ZipLoader,
4192
+ applyMixins,
4193
+ clamp,
4194
+ config,
4195
+ copyArray,
4196
+ copyProperty,
4197
+ folderName,
4198
+ logger,
4199
+ normalizeHitAreaDefs,
4200
+ rand,
4201
+ remove,
4202
+ resolveURL
4203
+ };