untitled-pixi-live2d-engine 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,23 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
2
7
  var __pow = Math.pow;
3
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
4
21
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
22
  var __async = (__this, __arguments, generator) => {
6
23
  return new Promise((resolve, reject) => {
@@ -22,7 +39,7 @@ var __async = (__this, __arguments, generator) => {
22
39
  step((generator = generator.apply(__this, __arguments)).next());
23
40
  });
24
41
  };
25
- import { EventEmitter, Matrix, loadTextures, Assets, Ticker, Transform, Point, Bounds, Container, ObservablePoint, WebGLRenderer } from "pixi.js";
42
+ import { EventEmitter, Matrix, loadTextures, Assets, Ticker, Transform, Point, Bounds, Container, ObservablePoint, WebGLRenderer, DOMAdapter, Texture, CanvasSource } from "pixi.js";
26
43
  import { sound, Sound, webaudio } from "@pixi/sound";
27
44
  const LOGICAL_WIDTH = 2;
28
45
  const LOGICAL_HEIGHT = 2;
@@ -89,7 +106,7 @@ const config = {
89
106
  preserveExpressionOnMotion: true,
90
107
  cubism: CubismFrameworkConfig
91
108
  };
92
- const VERSION = "1.0.1";
109
+ const VERSION = "1.1.0";
93
110
  const logger = {
94
111
  log(tag, ...messages) {
95
112
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -107,7 +124,7 @@ const logger = {
107
124
  }
108
125
  }
109
126
  };
110
- function clamp(num, lower, upper) {
127
+ function clamp$1(num, lower, upper) {
111
128
  return num < lower ? lower : num > upper ? upper : num;
112
129
  }
113
130
  function rand(min, max) {
@@ -382,8 +399,8 @@ class FocusController {
382
399
  * @param instant - Should the focus position be instantly applied.
383
400
  */
384
401
  focus(x, y, instant = false) {
385
- this.targetX = clamp(x, -1, 1);
386
- this.targetY = clamp(y, -1, 1);
402
+ this.targetX = clamp$1(x, -1, 1);
403
+ this.targetY = clamp$1(y, -1, 1);
387
404
  if (instant) {
388
405
  this.x = this.targetX;
389
406
  this.y = this.targetY;
@@ -1900,6 +1917,68 @@ class CubismLegacyModelSettings extends ModelSettings {
1900
1917
  }
1901
1918
  }
1902
1919
  }
1920
+ const DEFAULT_LOD_SCALE_THRESHOLD = 0.5;
1921
+ const DEFAULT_LOD_TEXTURE_SIZE_THRESHOLD = 4096;
1922
+ function getTextureLODPlan({
1923
+ lod,
1924
+ effectiveScale,
1925
+ textureWidth,
1926
+ textureHeight,
1927
+ lodScaleThreshold,
1928
+ lodTextureSizeThreshold,
1929
+ lodMaxLevel
1930
+ }) {
1931
+ if (getTextureLODMode(lod) !== "single-auto") {
1932
+ return void 0;
1933
+ }
1934
+ if (!Number.isFinite(effectiveScale) || effectiveScale <= 0) {
1935
+ return void 0;
1936
+ }
1937
+ const width = Math.floor(textureWidth);
1938
+ const height = Math.floor(textureHeight);
1939
+ if (width <= 1 || height <= 1) {
1940
+ return void 0;
1941
+ }
1942
+ const scaleThreshold = validPositive(lodScaleThreshold, DEFAULT_LOD_SCALE_THRESHOLD);
1943
+ if (effectiveScale >= scaleThreshold) {
1944
+ return void 0;
1945
+ }
1946
+ const textureSizeThreshold = validPositive(
1947
+ lodTextureSizeThreshold,
1948
+ DEFAULT_LOD_TEXTURE_SIZE_THRESHOLD
1949
+ );
1950
+ if (Math.max(width, height) < textureSizeThreshold) {
1951
+ return void 0;
1952
+ }
1953
+ const rawLevel = Math.round(Math.log2(1 / effectiveScale));
1954
+ const maxDimensionLevel = Math.max(1, Math.floor(Math.log2(Math.max(width, height))));
1955
+ const maxLevel = Math.min(maxDimensionLevel, validMaxLevel(lodMaxLevel, maxDimensionLevel));
1956
+ const level = clamp(Math.max(1, rawLevel), 1, maxLevel);
1957
+ const factor = __pow(2, level);
1958
+ return {
1959
+ level,
1960
+ width: Math.max(1, Math.round(width / factor)),
1961
+ height: Math.max(1, Math.round(height / factor))
1962
+ };
1963
+ }
1964
+ function getTextureLODMode(lod) {
1965
+ if (lod === false || lod === "single-auto") {
1966
+ return lod;
1967
+ }
1968
+ return "full";
1969
+ }
1970
+ function getTextureLODFilter(filter) {
1971
+ return filter === "nearest" ? "nearest" : "linear";
1972
+ }
1973
+ function validPositive(value, fallback) {
1974
+ return value !== void 0 && Number.isFinite(value) && value > 0 ? value : fallback;
1975
+ }
1976
+ function validMaxLevel(value, fallback) {
1977
+ return value !== void 0 && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
1978
+ }
1979
+ function clamp(value, min, max) {
1980
+ return Math.min(max, Math.max(min, value));
1981
+ }
1903
1982
  function createTexture(url, options = {}) {
1904
1983
  const config2 = loadTextures.config;
1905
1984
  const previousCrossOrigin = config2 == null ? void 0 : config2.crossOrigin;
@@ -1912,7 +1991,12 @@ function createTexture(url, options = {}) {
1912
1991
  config2.preferCreateImageBitmap = false;
1913
1992
  config2.preferWorkers = false;
1914
1993
  }
1915
- return Assets.load(url).catch((error) => {
1994
+ return Assets.load({
1995
+ src: url,
1996
+ data: {
1997
+ autoGenerateMipmaps: getTextureLODMode(options.lod) === "full"
1998
+ }
1999
+ }).catch((error) => {
1916
2000
  if (error instanceof Error) {
1917
2001
  throw error;
1918
2002
  }
@@ -1956,7 +2040,35 @@ const jsonToSettings = (context, next) => __async(null, null, function* () {
1956
2040
  return next();
1957
2041
  }
1958
2042
  }
1959
- throw new TypeError("Unknown settings format.");
2043
+ const url = context.source && typeof context.source.url === "string" ? context.source.url : void 0;
2044
+ const runtimeVersions = Live2DFactory.runtimes.map((r) => r.version).join(", ");
2045
+ if (Live2DFactory.runtimes.length === 0) {
2046
+ throw new TypeError(
2047
+ [
2048
+ "Unknown settings format: no Live2D runtimes registered.",
2049
+ 'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',
2050
+ url ? `Settings URL: ${url}` : void 0
2051
+ ].filter(Boolean).join("\n")
2052
+ );
2053
+ }
2054
+ const topLevelKeys = (() => {
2055
+ try {
2056
+ if (!context.source || typeof context.source !== "object" || Array.isArray(context.source)) {
2057
+ return void 0;
2058
+ }
2059
+ return Object.keys(context.source).slice(0, 30).join(", ");
2060
+ } catch (e) {
2061
+ return void 0;
2062
+ }
2063
+ })();
2064
+ throw new TypeError(
2065
+ [
2066
+ "Unknown settings format: no matching runtime found for the loaded settings JSON.",
2067
+ runtimeVersions ? `Registered runtimes (versions): ${runtimeVersions}` : void 0,
2068
+ topLevelKeys ? `Settings JSON keys: ${topLevelKeys}` : void 0,
2069
+ url ? `Settings URL: ${url}` : void 0
2070
+ ].filter(Boolean).join("\n")
2071
+ );
1960
2072
  });
1961
2073
  const waitUntilReady = (context, next) => {
1962
2074
  if (context.settings) {
@@ -2017,9 +2129,9 @@ const setupOptionals = (context, next) => __async(null, null, function* () {
2017
2129
  const setupEssentials = (context, next) => __async(null, null, function* () {
2018
2130
  if (context.settings) {
2019
2131
  const live2DModel = context.live2dModel;
2020
- const textureOptions = {
2132
+ const textureOptions = __spreadValues({
2021
2133
  crossOrigin: context.options.crossOrigin
2022
- };
2134
+ }, context.options.textureOptions);
2023
2135
  if (context.settings instanceof CubismLegacyModelSettings) {
2024
2136
  textureOptions.preferCreateImageBitmap = false;
2025
2137
  }
@@ -2654,6 +2766,61 @@ function ensureLive2DPipe(renderer) {
2654
2766
  r.renderPipes.live2d = new Live2DPipe(renderer);
2655
2767
  }
2656
2768
  }
2769
+ function getMatrixMaxScale(matrix) {
2770
+ return Math.max(Math.hypot(matrix.a, matrix.b), Math.hypot(matrix.c, matrix.d));
2771
+ }
2772
+ function isDrawableTextureResource(resource) {
2773
+ if (!resource || typeof resource !== "object") {
2774
+ return false;
2775
+ }
2776
+ const { width, height } = resource;
2777
+ return typeof width === "number" && width > 0 && typeof height === "number" && height > 0;
2778
+ }
2779
+ function createTextureLODTexture(sourceTexture, level, width, height, filter) {
2780
+ var _a, _b;
2781
+ const resource = sourceTexture.source.resource;
2782
+ if (!isDrawableTextureResource(resource)) {
2783
+ return void 0;
2784
+ }
2785
+ const canvas = DOMAdapter.get().createCanvas(width, height);
2786
+ const context = canvas.getContext("2d");
2787
+ if (!context) {
2788
+ return void 0;
2789
+ }
2790
+ try {
2791
+ context.clearRect(0, 0, width, height);
2792
+ context.imageSmoothingEnabled = filter !== "nearest";
2793
+ if ("imageSmoothingQuality" in context && filter !== "nearest") {
2794
+ context.imageSmoothingQuality = "high";
2795
+ }
2796
+ context.drawImage(
2797
+ resource,
2798
+ 0,
2799
+ 0,
2800
+ sourceTexture.source.pixelWidth,
2801
+ sourceTexture.source.pixelHeight,
2802
+ 0,
2803
+ 0,
2804
+ width,
2805
+ height
2806
+ );
2807
+ } catch (e) {
2808
+ return void 0;
2809
+ }
2810
+ const label = `${(_b = (_a = sourceTexture.label) != null ? _a : sourceTexture.source.label) != null ? _b : "Live2DTexture"} LOD ${level}`;
2811
+ return new Texture({
2812
+ label,
2813
+ source: new CanvasSource({
2814
+ resource: canvas,
2815
+ width,
2816
+ height,
2817
+ resolution: 1,
2818
+ scaleMode: getTextureLODFilter(filter),
2819
+ autoGenerateMipmaps: false,
2820
+ label
2821
+ })
2822
+ });
2823
+ }
2657
2824
  class Live2DModel extends Container {
2658
2825
  /**
2659
2826
  * Creates a new Live2DModel instance.
@@ -2677,6 +2844,9 @@ class Live2DModel extends Container {
2677
2844
  * @type {Texture[]}
2678
2845
  */
2679
2846
  __publicField(this, "textures", []);
2847
+ __publicField(this, "textureOptions");
2848
+ __publicField(this, "textureLODStates", []);
2849
+ __publicField(this, "textureLODFailures", []);
2680
2850
  /** @override
2681
2851
  * The Live2DTransform instance for this model.
2682
2852
  */
@@ -2733,15 +2903,25 @@ class Live2DModel extends Container {
2733
2903
  this.internalModel.updateWebGLContext(renderer.gl, this.generateUID());
2734
2904
  shouldUpdateTexture = true;
2735
2905
  }
2906
+ const { projectionMatrix, offset, worldTransformMatrix } = renderer.globalUniforms.globalUniformData;
2907
+ const adjustedWorld = tempWorldMatrix.copyFrom(worldTransformMatrix).append(this.groupTransform);
2908
+ const effectiveScale = getMatrixMaxScale(adjustedWorld) * renderer.resolution;
2736
2909
  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);
2910
+ const originalTexture = this.textures[i];
2911
+ let texture = this.resolveTextureForRender(i, originalTexture, effectiveScale);
2912
+ try {
2913
+ this.uploadTextureForRender(renderer, texture, shouldUpdateTexture);
2914
+ } catch (e) {
2915
+ if (texture === originalTexture) {
2916
+ throw new Error("Failed to upload Live2D texture.");
2917
+ }
2918
+ const state = this.textureLODStates[i];
2919
+ if ((state == null ? void 0 : state.texture) === texture) {
2920
+ this.markTextureLODFailure(i, originalTexture, state.level);
2921
+ this.destroyTextureLODState(i);
2922
+ }
2923
+ texture = originalTexture;
2924
+ this.uploadTextureForRender(renderer, texture, shouldUpdateTexture);
2745
2925
  }
2746
2926
  this.internalModel.bindTexture(i, renderer.texture.getGlSource(texture.source).texture);
2747
2927
  }
@@ -2758,8 +2938,6 @@ class Live2DModel extends Container {
2758
2938
  if (frameDelta) {
2759
2939
  this.internalModel.update(frameDelta, this.elapsedTime);
2760
2940
  }
2761
- const { projectionMatrix, offset } = renderer.globalUniforms.globalUniformData;
2762
- const adjustedWorld = tempWorldMatrix.copyFrom(this.worldTransform);
2763
2941
  adjustedWorld.tx -= (_a = offset == null ? void 0 : offset.x) != null ? _a : 0;
2764
2942
  adjustedWorld.ty -= (_b = offset == null ? void 0 : offset.y) != null ? _b : 0;
2765
2943
  const internalTransform = tempMatrix.copyFrom(projectionMatrix).append(adjustedWorld);
@@ -2782,6 +2960,7 @@ class Live2DModel extends Container {
2782
2960
  }
2783
2961
  }
2784
2962
  });
2963
+ this.textureOptions = options == null ? void 0 : options.textureOptions;
2785
2964
  this.anchor = new ObservablePoint(
2786
2965
  {
2787
2966
  _onUpdate: () => this.onAnchorChange()
@@ -3226,6 +3405,75 @@ class Live2DModel extends Container {
3226
3405
  this.deltaTime += dt;
3227
3406
  this.elapsedTime += dt;
3228
3407
  }
3408
+ resolveTextureForRender(index, texture, effectiveScale) {
3409
+ var _a;
3410
+ const plan = getTextureLODPlan(__spreadProps(__spreadValues({}, this.textureOptions), {
3411
+ effectiveScale,
3412
+ textureWidth: texture.source.pixelWidth,
3413
+ textureHeight: texture.source.pixelHeight
3414
+ }));
3415
+ if (!plan) {
3416
+ return texture;
3417
+ }
3418
+ const failure = this.textureLODFailures[index];
3419
+ if ((failure == null ? void 0 : failure.source) === texture && failure.levels.has(plan.level)) {
3420
+ return texture;
3421
+ }
3422
+ const existing = this.textureLODStates[index];
3423
+ if ((existing == null ? void 0 : existing.source) === texture && existing.level === plan.level && !existing.texture.destroyed) {
3424
+ return existing.texture;
3425
+ }
3426
+ this.destroyTextureLODState(index);
3427
+ const lodTexture = createTextureLODTexture(
3428
+ texture,
3429
+ plan.level,
3430
+ plan.width,
3431
+ plan.height,
3432
+ (_a = this.textureOptions) == null ? void 0 : _a.lodFilter
3433
+ );
3434
+ if (!lodTexture) {
3435
+ this.markTextureLODFailure(index, texture, plan.level);
3436
+ return texture;
3437
+ }
3438
+ this.textureLODStates[index] = {
3439
+ source: texture,
3440
+ level: plan.level,
3441
+ texture: lodTexture
3442
+ };
3443
+ return lodTexture;
3444
+ }
3445
+ markTextureLODFailure(index, texture, level) {
3446
+ let failure = this.textureLODFailures[index];
3447
+ if ((failure == null ? void 0 : failure.source) !== texture) {
3448
+ failure = { source: texture, levels: /* @__PURE__ */ new Set() };
3449
+ this.textureLODFailures[index] = failure;
3450
+ }
3451
+ failure.levels.add(level);
3452
+ }
3453
+ destroyTextureLODState(index) {
3454
+ const state = this.textureLODStates[index];
3455
+ if (!state) {
3456
+ return;
3457
+ }
3458
+ state.texture.destroy(true);
3459
+ this.textureLODStates[index] = void 0;
3460
+ }
3461
+ destroyTextureLODStates() {
3462
+ for (let i = 0; i < this.textureLODStates.length; i++) {
3463
+ this.destroyTextureLODState(i);
3464
+ }
3465
+ this.textureLODFailures.length = 0;
3466
+ }
3467
+ uploadTextureForRender(renderer, texture, shouldUpdateTexture) {
3468
+ const hasGlSource = Boolean(texture.source._gpuData[renderer.uid]);
3469
+ if (shouldUpdateTexture || !hasGlSource) {
3470
+ renderer.gl.pixelStorei(
3471
+ WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,
3472
+ this.internalModel.textureFlipY
3473
+ );
3474
+ renderer.texture.bind(texture, 0);
3475
+ }
3476
+ }
3229
3477
  /**
3230
3478
  * Destroys the model and all related resources. This takes the same options and also
3231
3479
  * behaves the same as `PIXI.Container#destroy`.
@@ -3240,6 +3488,7 @@ class Live2DModel extends Container {
3240
3488
  */
3241
3489
  destroy(options) {
3242
3490
  this.emit("destroy");
3491
+ this.destroyTextureLODStates();
3243
3492
  if (options == null ? void 0 : options.texture) {
3244
3493
  this.textures.forEach((texture) => texture.destroy(options.baseTexture));
3245
3494
  }
@@ -3605,7 +3854,7 @@ class Live2DEyeBlink {
3605
3854
  this.rightParam = coreModel.getParamIndex("PARAM_EYE_R_OPEN");
3606
3855
  }
3607
3856
  setEyeParams(value) {
3608
- this.eyeParamValue = clamp(value, 0, 1);
3857
+ this.eyeParamValue = clamp$1(value, 0, 1);
3609
3858
  this.coreModel.setParamFloat(this.leftParam, this.eyeParamValue);
3610
3859
  this.coreModel.setParamFloat(this.rightParam, this.eyeParamValue);
3611
3860
  }
@@ -3695,6 +3944,12 @@ class CubismLegacyInternalModel extends InternalModel {
3695
3944
  { breathDepth: 1, lipSyncGain: 1.5, lipSyncWeight: 0.4 },
3696
3945
  options
3697
3946
  );
3947
+ if ((options == null ? void 0 : options.useHighPrecisionMask) !== void 0 && options.useHighPrecisionMask !== false) {
3948
+ logger.warn(
3949
+ "CubismLegacyInternalModel",
3950
+ "`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."
3951
+ );
3952
+ }
3698
3953
  this.motionManager = new CubismLegacyMotionManager(this);
3699
3954
  this.parallelMotionManager = [];
3700
3955
  this.eyeBlink = new Live2DEyeBlink(coreModel);
@@ -3832,7 +4087,7 @@ class CubismLegacyInternalModel extends InternalModel {
3832
4087
  const max_ = 1;
3833
4088
  const min_ = value > 0 ? 0.1 : 0;
3834
4089
  value = Math.pow(value, 1.15);
3835
- value = clamp(value, min_, max_);
4090
+ value = clamp$1(value, min_, max_);
3836
4091
  for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) {
3837
4092
  this.coreModel.addToParamFloat(
3838
4093
  this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]),
@@ -4072,7 +4327,7 @@ class Live2DPose {
4072
4327
  );
4073
4328
  if (visibleIndex >= 0) {
4074
4329
  const originalOpacity = model.getPartsOpacity(partsGroup[visibleIndex].partsIndex);
4075
- visibleOpacity = clamp(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
4330
+ visibleOpacity = clamp$1(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
4076
4331
  } else {
4077
4332
  visibleIndex = 0;
4078
4333
  visibleOpacity = 1;
@@ -4193,7 +4448,7 @@ export {
4193
4448
  XHRLoader,
4194
4449
  ZipLoader,
4195
4450
  applyMixins,
4196
- clamp,
4451
+ clamp$1 as clamp,
4197
4452
  config,
4198
4453
  copyArray,
4199
4454
  copyProperty,