cubism2.es.js 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122
  1. var __pow = Math.pow;
  2. var __async = (__this, __arguments, generator) => {
  3. return new Promise((resolve, reject) => {
  4. var fulfilled = (value) => {
  5. try {
  6. step(generator.next(value));
  7. } catch (e) {
  8. reject(e);
  9. }
  10. };
  11. var rejected = (value) => {
  12. try {
  13. step(generator.throw(value));
  14. } catch (e) {
  15. reject(e);
  16. }
  17. };
  18. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  19. step((generator = generator.apply(__this, __arguments)).next());
  20. });
  21. };
  22. import { EventEmitter, url } from "@pixi/utils";
  23. import { Matrix, Transform, Point, ObservablePoint } from "@pixi/math";
  24. import { Texture } from "@pixi/core";
  25. import { Container } from "@pixi/display";
  26. const LOGICAL_WIDTH = 2;
  27. const LOGICAL_HEIGHT = 2;
  28. var CubismConfig;
  29. ((CubismConfig2) => {
  30. CubismConfig2.supportMoreMaskDivisions = true;
  31. CubismConfig2.setOpacityFromMotion = false;
  32. })(CubismConfig || (CubismConfig = {}));
  33. var config;
  34. ((config2) => {
  35. config2.LOG_LEVEL_VERBOSE = 0;
  36. config2.LOG_LEVEL_WARNING = 1;
  37. config2.LOG_LEVEL_ERROR = 2;
  38. config2.LOG_LEVEL_NONE = 999;
  39. config2.logLevel = config2.LOG_LEVEL_WARNING;
  40. config2.sound = true;
  41. config2.motionSync = true;
  42. config2.motionFadingDuration = 500;
  43. config2.idleMotionFadingDuration = 2e3;
  44. config2.expressionFadingDuration = 500;
  45. config2.preserveExpressionOnMotion = true;
  46. config2.cubism4 = CubismConfig;
  47. })(config || (config = {}));
  48. const VERSION = "0.4.0";
  49. const logger = {
  50. log(tag, ...messages) {
  51. if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
  52. console.log(`[${tag}]`, ...messages);
  53. }
  54. },
  55. warn(tag, ...messages) {
  56. if (config.logLevel <= config.LOG_LEVEL_WARNING) {
  57. console.warn(`[${tag}]`, ...messages);
  58. }
  59. },
  60. error(tag, ...messages) {
  61. if (config.logLevel <= config.LOG_LEVEL_ERROR) {
  62. console.error(`[${tag}]`, ...messages);
  63. }
  64. }
  65. };
  66. function clamp(num, lower, upper) {
  67. return num < lower ? lower : num > upper ? upper : num;
  68. }
  69. function rand(min, max) {
  70. return Math.random() * (max - min) + min;
  71. }
  72. function copyProperty(type, from, to, fromKey, toKey) {
  73. const value = from[fromKey];
  74. if (value !== null && typeof value === type) {
  75. to[toKey] = value;
  76. }
  77. }
  78. function copyArray(type, from, to, fromKey, toKey) {
  79. const array = from[fromKey];
  80. if (Array.isArray(array)) {
  81. to[toKey] = array.filter((item) => item !== null && typeof item === type);
  82. }
  83. }
  84. function applyMixins(derivedCtor, baseCtors) {
  85. baseCtors.forEach((baseCtor) => {
  86. Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
  87. if (name !== "constructor") {
  88. Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
  89. }
  90. });
  91. });
  92. }
  93. function folderName(url2) {
  94. let lastSlashIndex = url2.lastIndexOf("/");
  95. if (lastSlashIndex != -1) {
  96. url2 = url2.slice(0, lastSlashIndex);
  97. }
  98. lastSlashIndex = url2.lastIndexOf("/");
  99. if (lastSlashIndex !== -1) {
  100. url2 = url2.slice(lastSlashIndex + 1);
  101. }
  102. return url2;
  103. }
  104. function remove(array, item) {
  105. const index = array.indexOf(item);
  106. if (index !== -1) {
  107. array.splice(index, 1);
  108. }
  109. }
  110. class ExpressionManager extends EventEmitter {
  111. constructor(settings, options) {
  112. super();
  113. this.expressions = [];
  114. this.reserveExpressionIndex = -1;
  115. this.destroyed = false;
  116. this.settings = settings;
  117. this.tag = `ExpressionManager(${settings.name})`;
  118. }
  119. init() {
  120. this.defaultExpression = this.createExpression({}, void 0);
  121. this.currentExpression = this.defaultExpression;
  122. this.stopAllExpressions();
  123. }
  124. loadExpression(index) {
  125. return __async(this, null, function* () {
  126. if (!this.definitions[index]) {
  127. logger.warn(this.tag, `Undefined expression at [${index}]`);
  128. return void 0;
  129. }
  130. if (this.expressions[index] === null) {
  131. logger.warn(this.tag, `Cannot set expression at [${index}] because it's already failed in loading.`);
  132. return void 0;
  133. }
  134. if (this.expressions[index]) {
  135. return this.expressions[index];
  136. }
  137. const expression = yield this._loadExpression(index);
  138. this.expressions[index] = expression;
  139. return expression;
  140. });
  141. }
  142. _loadExpression(index) {
  143. throw new Error("Not implemented.");
  144. }
  145. setRandomExpression() {
  146. return __async(this, null, function* () {
  147. if (this.definitions.length) {
  148. const availableIndices = [];
  149. for (let i = 0; i < this.definitions.length; i++) {
  150. if (this.expressions[i] !== null && this.expressions[i] !== this.currentExpression && i !== this.reserveExpressionIndex) {
  151. availableIndices.push(i);
  152. }
  153. }
  154. if (availableIndices.length) {
  155. const index = Math.floor(Math.random() * availableIndices.length);
  156. return this.setExpression(index);
  157. }
  158. }
  159. return false;
  160. });
  161. }
  162. resetExpression() {
  163. this._setExpression(this.defaultExpression);
  164. }
  165. restoreExpression() {
  166. this._setExpression(this.currentExpression);
  167. }
  168. setExpression(index) {
  169. return __async(this, null, function* () {
  170. if (typeof index !== "number") {
  171. index = this.getExpressionIndex(index);
  172. }
  173. if (!(index > -1 && index < this.definitions.length)) {
  174. return false;
  175. }
  176. if (index === this.expressions.indexOf(this.currentExpression)) {
  177. return false;
  178. }
  179. this.reserveExpressionIndex = index;
  180. const expression = yield this.loadExpression(index);
  181. if (!expression || this.reserveExpressionIndex !== index) {
  182. return false;
  183. }
  184. this.reserveExpressionIndex = -1;
  185. this.currentExpression = expression;
  186. this._setExpression(expression);
  187. return true;
  188. });
  189. }
  190. update(model, now) {
  191. if (!this.isFinished()) {
  192. return this.updateParameters(model, now);
  193. }
  194. return false;
  195. }
  196. destroy() {
  197. this.destroyed = true;
  198. this.emit("destroy");
  199. const self = this;
  200. self.definitions = void 0;
  201. self.expressions = void 0;
  202. }
  203. }
  204. const EPSILON = 0.01;
  205. const MAX_SPEED = 40 / 7.5;
  206. const ACCELERATION_TIME = 1 / (0.15 * 1e3);
  207. class FocusController {
  208. constructor() {
  209. this.targetX = 0;
  210. this.targetY = 0;
  211. this.x = 0;
  212. this.y = 0;
  213. this.vx = 0;
  214. this.vy = 0;
  215. }
  216. focus(x, y, instant = false) {
  217. this.targetX = clamp(x, -1, 1);
  218. this.targetY = clamp(y, -1, 1);
  219. if (instant) {
  220. this.x = this.targetX;
  221. this.y = this.targetY;
  222. }
  223. }
  224. update(dt) {
  225. const dx = this.targetX - this.x;
  226. const dy = this.targetY - this.y;
  227. if (Math.abs(dx) < EPSILON && Math.abs(dy) < EPSILON)
  228. return;
  229. const d = Math.sqrt(__pow(dx, 2) + __pow(dy, 2));
  230. const maxSpeed = MAX_SPEED / (1e3 / dt);
  231. let ax = maxSpeed * (dx / d) - this.vx;
  232. let ay = maxSpeed * (dy / d) - this.vy;
  233. const a = Math.sqrt(__pow(ax, 2) + __pow(ay, 2));
  234. const maxA = maxSpeed * ACCELERATION_TIME * dt;
  235. if (a > maxA) {
  236. ax *= maxA / a;
  237. ay *= maxA / a;
  238. }
  239. this.vx += ax;
  240. this.vy += ay;
  241. const v = Math.sqrt(__pow(this.vx, 2) + __pow(this.vy, 2));
  242. const maxV = 0.5 * (Math.sqrt(__pow(maxA, 2) + 8 * maxA * d) - maxA);
  243. if (v > maxV) {
  244. this.vx *= maxV / v;
  245. this.vy *= maxV / v;
  246. }
  247. this.x += this.vx;
  248. this.y += this.vy;
  249. }
  250. }
  251. class ModelSettings {
  252. constructor(json) {
  253. this.json = json;
  254. let url2 = json.url;
  255. if (typeof url2 !== "string") {
  256. throw new TypeError("The `url` field in settings JSON must be defined as a string.");
  257. }
  258. this.url = url2;
  259. this.name = folderName(this.url);
  260. }
  261. resolveURL(path) {
  262. return url.resolve(this.url, path);
  263. }
  264. replaceFiles(replacer) {
  265. this.moc = replacer(this.moc, "moc");
  266. if (this.pose !== void 0) {
  267. this.pose = replacer(this.pose, "pose");
  268. }
  269. if (this.physics !== void 0) {
  270. this.physics = replacer(this.physics, "physics");
  271. }
  272. for (let i = 0; i < this.textures.length; i++) {
  273. this.textures[i] = replacer(this.textures[i], `textures[${i}]`);
  274. }
  275. }
  276. getDefinedFiles() {
  277. const files = [];
  278. this.replaceFiles((file) => {
  279. files.push(file);
  280. return file;
  281. });
  282. return files;
  283. }
  284. validateFiles(files) {
  285. const assertFileExists = (expectedFile, shouldThrow) => {
  286. const actualPath = this.resolveURL(expectedFile);
  287. if (!files.includes(actualPath)) {
  288. if (shouldThrow) {
  289. throw new Error(`File "${expectedFile}" is defined in settings, but doesn't exist in given files`);
  290. }
  291. return false;
  292. }
  293. return true;
  294. };
  295. const essentialFiles = [this.moc, ...this.textures];
  296. essentialFiles.forEach((texture) => assertFileExists(texture, true));
  297. const definedFiles = this.getDefinedFiles();
  298. return definedFiles.filter((file) => assertFileExists(file, false));
  299. }
  300. }
  301. var MotionPriority = /* @__PURE__ */ ((MotionPriority2) => {
  302. MotionPriority2[MotionPriority2["NONE"] = 0] = "NONE";
  303. MotionPriority2[MotionPriority2["IDLE"] = 1] = "IDLE";
  304. MotionPriority2[MotionPriority2["NORMAL"] = 2] = "NORMAL";
  305. MotionPriority2[MotionPriority2["FORCE"] = 3] = "FORCE";
  306. return MotionPriority2;
  307. })(MotionPriority || {});
  308. class MotionState {
  309. constructor() {
  310. this.debug = false;
  311. this.currentPriority = 0;
  312. this.reservePriority = 0;
  313. }
  314. reserve(group, index, priority) {
  315. if (priority <= 0) {
  316. logger.log(this.tag, `Cannot start a motion with MotionPriority.NONE.`);
  317. return false;
  318. }
  319. if (group === this.currentGroup && index === this.currentIndex) {
  320. logger.log(this.tag, `Motion is already playing.`, this.dump(group, index));
  321. return false;
  322. }
  323. if (group === this.reservedGroup && index === this.reservedIndex || group === this.reservedIdleGroup && index === this.reservedIdleIndex) {
  324. logger.log(this.tag, `Motion is already reserved.`, this.dump(group, index));
  325. return false;
  326. }
  327. if (priority === 1) {
  328. if (this.currentPriority !== 0) {
  329. logger.log(this.tag, `Cannot start idle motion because another motion is playing.`, this.dump(group, index));
  330. return false;
  331. }
  332. if (this.reservedIdleGroup !== void 0) {
  333. logger.log(this.tag, `Cannot start idle motion because another idle motion has reserved.`, this.dump(group, index));
  334. return false;
  335. }
  336. this.setReservedIdle(group, index);
  337. } else {
  338. if (priority < 3) {
  339. if (priority <= this.currentPriority) {
  340. logger.log(this.tag, "Cannot start motion because another motion is playing as an equivalent or higher priority.", this.dump(group, index));
  341. return false;
  342. }
  343. if (priority <= this.reservePriority) {
  344. logger.log(this.tag, "Cannot start motion because another motion has reserved as an equivalent or higher priority.", this.dump(group, index));
  345. return false;
  346. }
  347. }
  348. this.setReserved(group, index, priority);
  349. }
  350. return true;
  351. }
  352. start(motion, group, index, priority) {
  353. if (priority === 1) {
  354. this.setReservedIdle(void 0, void 0);
  355. if (this.currentPriority !== 0) {
  356. logger.log(this.tag, "Cannot start idle motion because another motion is playing.", this.dump(group, index));
  357. return false;
  358. }
  359. } else {
  360. if (group !== this.reservedGroup || index !== this.reservedIndex) {
  361. logger.log(this.tag, "Cannot start motion because another motion has taken the place.", this.dump(group, index));
  362. return false;
  363. }
  364. this.setReserved(void 0, void 0, 0);
  365. }
  366. if (!motion) {
  367. return false;
  368. }
  369. this.setCurrent(group, index, priority);
  370. return true;
  371. }
  372. complete() {
  373. this.setCurrent(void 0, void 0, 0);
  374. }
  375. setCurrent(group, index, priority) {
  376. this.currentPriority = priority;
  377. this.currentGroup = group;
  378. this.currentIndex = index;
  379. }
  380. setReserved(group, index, priority) {
  381. this.reservePriority = priority;
  382. this.reservedGroup = group;
  383. this.reservedIndex = index;
  384. }
  385. setReservedIdle(group, index) {
  386. this.reservedIdleGroup = group;
  387. this.reservedIdleIndex = index;
  388. }
  389. isActive(group, index) {
  390. return group === this.currentGroup && index === this.currentIndex || group === this.reservedGroup && index === this.reservedIndex || group === this.reservedIdleGroup && index === this.reservedIdleIndex;
  391. }
  392. reset() {
  393. this.setCurrent(void 0, void 0, 0);
  394. this.setReserved(void 0, void 0, 0);
  395. this.setReservedIdle(void 0, void 0);
  396. }
  397. shouldRequestIdleMotion() {
  398. return this.currentGroup === void 0 && this.reservedIdleGroup === void 0;
  399. }
  400. shouldOverrideExpression() {
  401. return !config.preserveExpressionOnMotion && this.currentPriority > 1;
  402. }
  403. dump(requestedGroup, requestedIndex) {
  404. if (this.debug) {
  405. const keys = [
  406. "currentPriority",
  407. "reservePriority",
  408. "currentGroup",
  409. "currentIndex",
  410. "reservedGroup",
  411. "reservedIndex",
  412. "reservedIdleGroup",
  413. "reservedIdleIndex"
  414. ];
  415. return `
  416. <Requested> group = "${requestedGroup}", index = ${requestedIndex}
  417. ` + keys.map((key) => "[" + key + "] " + this[key]).join("\n");
  418. }
  419. return "";
  420. }
  421. }
  422. const TAG$2 = "SoundManager";
  423. const VOLUME = 0.5;
  424. class SoundManager {
  425. static get volume() {
  426. return this._volume;
  427. }
  428. static set volume(value) {
  429. this._volume = (value > 1 ? 1 : value < 0 ? 0 : value) || 0;
  430. this.audios.forEach((audio) => audio.volume = this._volume);
  431. }
  432. static add(file, onFinish, onError) {
  433. const audio = new Audio(file);
  434. audio.volume = this._volume;
  435. audio.preload = "auto";
  436. audio.addEventListener("ended", () => {
  437. this.dispose(audio);
  438. onFinish == null ? void 0 : onFinish();
  439. });
  440. audio.addEventListener("error", (e) => {
  441. this.dispose(audio);
  442. logger.warn(TAG$2, `Error occurred on "${file}"`, e.error);
  443. onError == null ? void 0 : onError(e.error);
  444. });
  445. this.audios.push(audio);
  446. return audio;
  447. }
  448. static play(audio) {
  449. return new Promise((resolve, reject) => {
  450. var _a;
  451. (_a = audio.play()) == null ? void 0 : _a.catch((e) => {
  452. audio.dispatchEvent(new ErrorEvent("error", { error: e }));
  453. reject(e);
  454. });
  455. if (audio.readyState === audio.HAVE_ENOUGH_DATA) {
  456. resolve();
  457. } else {
  458. audio.addEventListener("canplaythrough", resolve);
  459. }
  460. });
  461. }
  462. static dispose(audio) {
  463. audio.pause();
  464. audio.removeAttribute("src");
  465. remove(this.audios, audio);
  466. }
  467. static destroy() {
  468. for (let i = this.audios.length - 1; i >= 0; i--) {
  469. this.dispose(this.audios[i]);
  470. }
  471. }
  472. }
  473. SoundManager.audios = [];
  474. SoundManager._volume = VOLUME;
  475. var MotionPreloadStrategy = /* @__PURE__ */ ((MotionPreloadStrategy2) => {
  476. MotionPreloadStrategy2["ALL"] = "ALL";
  477. MotionPreloadStrategy2["IDLE"] = "IDLE";
  478. MotionPreloadStrategy2["NONE"] = "NONE";
  479. return MotionPreloadStrategy2;
  480. })(MotionPreloadStrategy || {});
  481. class MotionManager extends EventEmitter {
  482. constructor(settings, options) {
  483. super();
  484. this.motionGroups = {};
  485. this.state = new MotionState();
  486. this.playing = false;
  487. this.destroyed = false;
  488. this.settings = settings;
  489. this.tag = `MotionManager(${settings.name})`;
  490. this.state.tag = this.tag;
  491. }
  492. init(options) {
  493. if (options == null ? void 0 : options.idleMotionGroup) {
  494. this.groups.idle = options.idleMotionGroup;
  495. }
  496. this.setupMotions(options);
  497. this.stopAllMotions();
  498. }
  499. setupMotions(options) {
  500. for (const group of Object.keys(this.definitions)) {
  501. this.motionGroups[group] = [];
  502. }
  503. let groups;
  504. switch (options == null ? void 0 : options.motionPreload) {
  505. case "NONE":
  506. return;
  507. case "ALL":
  508. groups = Object.keys(this.definitions);
  509. break;
  510. case "IDLE":
  511. default:
  512. groups = [this.groups.idle];
  513. break;
  514. }
  515. for (const group of groups) {
  516. if (this.definitions[group]) {
  517. for (let i = 0; i < this.definitions[group].length; i++) {
  518. this.loadMotion(group, i).then();
  519. }
  520. }
  521. }
  522. }
  523. loadMotion(group, index) {
  524. return __async(this, null, function* () {
  525. var _a;
  526. if (!((_a = this.definitions[group]) == null ? void 0 : _a[index])) {
  527. logger.warn(this.tag, `Undefined motion at "${group}"[${index}]`);
  528. return void 0;
  529. }
  530. if (this.motionGroups[group][index] === null) {
  531. logger.warn(this.tag, `Cannot start motion at "${group}"[${index}] because it's already failed in loading.`);
  532. return void 0;
  533. }
  534. if (this.motionGroups[group][index]) {
  535. return this.motionGroups[group][index];
  536. }
  537. const motion = yield this._loadMotion(group, index);
  538. if (this.destroyed) {
  539. return;
  540. }
  541. this.motionGroups[group][index] = motion != null ? motion : null;
  542. return motion;
  543. });
  544. }
  545. _loadMotion(group, index) {
  546. throw new Error("Not implemented.");
  547. }
  548. startMotion(_0, _1) {
  549. return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL) {
  550. var _a;
  551. if (!this.state.reserve(group, index, priority)) {
  552. return false;
  553. }
  554. const definition = (_a = this.definitions[group]) == null ? void 0 : _a[index];
  555. if (!definition) {
  556. return false;
  557. }
  558. if (this.currentAudio) {
  559. SoundManager.dispose(this.currentAudio);
  560. }
  561. let audio;
  562. if (config.sound) {
  563. const soundURL = this.getSoundFile(definition);
  564. if (soundURL) {
  565. try {
  566. audio = SoundManager.add(this.settings.resolveURL(soundURL), () => this.currentAudio = void 0, () => this.currentAudio = void 0);
  567. this.currentAudio = audio;
  568. } catch (e) {
  569. logger.warn(this.tag, "Failed to create audio", soundURL, e);
  570. }
  571. }
  572. }
  573. const motion = yield this.loadMotion(group, index);
  574. if (audio) {
  575. const readyToPlay = SoundManager.play(audio).catch((e) => logger.warn(this.tag, "Failed to play audio", audio.src, e));
  576. if (config.motionSync) {
  577. yield readyToPlay;
  578. }
  579. }
  580. if (!this.state.start(motion, group, index, priority)) {
  581. if (audio) {
  582. SoundManager.dispose(audio);
  583. this.currentAudio = void 0;
  584. }
  585. return false;
  586. }
  587. logger.log(this.tag, "Start motion:", this.getMotionName(definition));
  588. this.emit("motionStart", group, index, audio);
  589. if (this.state.shouldOverrideExpression()) {
  590. this.expressionManager && this.expressionManager.resetExpression();
  591. }
  592. this.playing = true;
  593. this._startMotion(motion);
  594. return true;
  595. });
  596. }
  597. startRandomMotion(group, priority) {
  598. return __async(this, null, function* () {
  599. const groupDefs = this.definitions[group];
  600. if (groupDefs == null ? void 0 : groupDefs.length) {
  601. const availableIndices = [];
  602. for (let i = 0; i < groupDefs.length; i++) {
  603. if (this.motionGroups[group][i] !== null && !this.state.isActive(group, i)) {
  604. availableIndices.push(i);
  605. }
  606. }
  607. if (availableIndices.length) {
  608. const index = Math.floor(Math.random() * availableIndices.length);
  609. return this.startMotion(group, availableIndices[index], priority);
  610. }
  611. }
  612. return false;
  613. });
  614. }
  615. stopAllMotions() {
  616. this._stopAllMotions();
  617. this.state.reset();
  618. if (this.currentAudio) {
  619. SoundManager.dispose(this.currentAudio);
  620. this.currentAudio = void 0;
  621. }
  622. }
  623. update(model, now) {
  624. var _a;
  625. if (this.isFinished()) {
  626. if (this.playing) {
  627. this.playing = false;
  628. this.emit("motionFinish");
  629. }
  630. if (this.state.shouldOverrideExpression()) {
  631. (_a = this.expressionManager) == null ? void 0 : _a.restoreExpression();
  632. }
  633. this.state.complete();
  634. if (this.state.shouldRequestIdleMotion()) {
  635. this.startRandomMotion(this.groups.idle, MotionPriority.IDLE);
  636. }
  637. }
  638. return this.updateParameters(model, now);
  639. }
  640. destroy() {
  641. var _a;
  642. this.destroyed = true;
  643. this.emit("destroy");
  644. this.stopAllMotions();
  645. (_a = this.expressionManager) == null ? void 0 : _a.destroy();
  646. const self = this;
  647. self.definitions = void 0;
  648. self.motionGroups = void 0;
  649. }
  650. }
  651. const tempBounds = { x: 0, y: 0, width: 0, height: 0 };
  652. class InternalModel extends EventEmitter {
  653. constructor() {
  654. super(...arguments);
  655. this.focusController = new FocusController();
  656. this.originalWidth = 0;
  657. this.originalHeight = 0;
  658. this.width = 0;
  659. this.height = 0;
  660. this.localTransform = new Matrix();
  661. this.drawingMatrix = new Matrix();
  662. this.hitAreas = {};
  663. this.textureFlipY = false;
  664. this.viewport = [0, 0, 0, 0];
  665. this.destroyed = false;
  666. }
  667. init() {
  668. this.setupLayout();
  669. this.setupHitAreas();
  670. }
  671. setupLayout() {
  672. const self = this;
  673. const size = this.getSize();
  674. self.originalWidth = size[0];
  675. self.originalHeight = size[1];
  676. const layout = Object.assign({
  677. width: LOGICAL_WIDTH,
  678. height: LOGICAL_HEIGHT
  679. }, this.getLayout());
  680. this.localTransform.scale(layout.width / LOGICAL_WIDTH, layout.height / LOGICAL_HEIGHT);
  681. self.width = this.originalWidth * this.localTransform.a;
  682. self.height = this.originalHeight * this.localTransform.d;
  683. 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;
  684. 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;
  685. this.localTransform.translate(this.width * offsetX, -this.height * offsetY);
  686. }
  687. setupHitAreas() {
  688. const definitions = this.getHitAreaDefs().filter((hitArea) => hitArea.index >= 0);
  689. for (const def of definitions) {
  690. this.hitAreas[def.name] = def;
  691. }
  692. }
  693. hitTest(x, y) {
  694. return Object.keys(this.hitAreas).filter((hitAreaName) => this.isHit(hitAreaName, x, y));
  695. }
  696. isHit(hitAreaName, x, y) {
  697. if (!this.hitAreas[hitAreaName]) {
  698. return false;
  699. }
  700. const drawIndex = this.hitAreas[hitAreaName].index;
  701. const bounds = this.getDrawableBounds(drawIndex, tempBounds);
  702. return bounds.x <= x && x <= bounds.x + bounds.width && bounds.y <= y && y <= bounds.y + bounds.height;
  703. }
  704. getDrawableBounds(index, bounds) {
  705. const vertices = this.getDrawableVertices(index);
  706. let left = vertices[0];
  707. let right = vertices[0];
  708. let top = vertices[1];
  709. let bottom = vertices[1];
  710. for (let i = 0; i < vertices.length; i += 2) {
  711. const vx = vertices[i];
  712. const vy = vertices[i + 1];
  713. left = Math.min(vx, left);
  714. right = Math.max(vx, right);
  715. top = Math.min(vy, top);
  716. bottom = Math.max(vy, bottom);
  717. }
  718. bounds != null ? bounds : bounds = {};
  719. bounds.x = left;
  720. bounds.y = top;
  721. bounds.width = right - left;
  722. bounds.height = bottom - top;
  723. return bounds;
  724. }
  725. updateTransform(transform) {
  726. this.drawingMatrix.copyFrom(transform).append(this.localTransform);
  727. }
  728. update(dt, now) {
  729. this.focusController.update(dt);
  730. }
  731. destroy() {
  732. this.destroyed = true;
  733. this.emit("destroy");
  734. this.motionManager.destroy();
  735. this.motionManager = void 0;
  736. }
  737. }
  738. const TAG$1 = "XHRLoader";
  739. class NetworkError extends Error {
  740. constructor(message, url2, status, aborted = false) {
  741. super(message);
  742. this.url = url2;
  743. this.status = status;
  744. this.aborted = aborted;
  745. }
  746. }
  747. const _XHRLoader = class {
  748. static createXHR(target, url2, type, onload, onerror) {
  749. const xhr = new XMLHttpRequest();
  750. _XHRLoader.allXhrSet.add(xhr);
  751. if (target) {
  752. let xhrSet = _XHRLoader.xhrMap.get(target);
  753. if (!xhrSet) {
  754. xhrSet = /* @__PURE__ */ new Set([xhr]);
  755. _XHRLoader.xhrMap.set(target, xhrSet);
  756. } else {
  757. xhrSet.add(xhr);
  758. }
  759. if (!target.listeners("destroy").includes(_XHRLoader.cancelXHRs)) {
  760. target.once("destroy", _XHRLoader.cancelXHRs);
  761. }
  762. }
  763. xhr.open("GET", url2);
  764. xhr.responseType = type;
  765. xhr.onload = () => {
  766. if ((xhr.status === 200 || xhr.status === 0) && xhr.response) {
  767. onload(xhr.response);
  768. } else {
  769. xhr.onerror();
  770. }
  771. };
  772. xhr.onerror = () => {
  773. logger.warn(TAG$1, `Failed to load resource as ${xhr.responseType} (Status ${xhr.status}): ${url2}`);
  774. onerror(new NetworkError("Network error.", url2, xhr.status));
  775. };
  776. xhr.onabort = () => onerror(new NetworkError("Aborted.", url2, xhr.status, true));
  777. xhr.onloadend = () => {
  778. var _a;
  779. _XHRLoader.allXhrSet.delete(xhr);
  780. if (target) {
  781. (_a = _XHRLoader.xhrMap.get(target)) == null ? void 0 : _a.delete(xhr);
  782. }
  783. };
  784. return xhr;
  785. }
  786. static cancelXHRs() {
  787. var _a;
  788. (_a = _XHRLoader.xhrMap.get(this)) == null ? void 0 : _a.forEach((xhr) => {
  789. xhr.abort();
  790. _XHRLoader.allXhrSet.delete(xhr);
  791. });
  792. _XHRLoader.xhrMap.delete(this);
  793. }
  794. static release() {
  795. _XHRLoader.allXhrSet.forEach((xhr) => xhr.abort());
  796. _XHRLoader.allXhrSet.clear();
  797. _XHRLoader.xhrMap = /* @__PURE__ */ new WeakMap();
  798. }
  799. };
  800. let XHRLoader = _XHRLoader;
  801. XHRLoader.xhrMap = /* @__PURE__ */ new WeakMap();
  802. XHRLoader.allXhrSet = /* @__PURE__ */ new Set();
  803. XHRLoader.loader = (context, next) => {
  804. return new Promise((resolve, reject) => {
  805. const xhr = _XHRLoader.createXHR(context.target, context.settings ? context.settings.resolveURL(context.url) : context.url, context.type, (data) => {
  806. context.result = data;
  807. resolve();
  808. }, reject);
  809. xhr.send();
  810. });
  811. };
  812. function runMiddlewares(middleware, context) {
  813. let index = -1;
  814. return dispatch(0);
  815. function dispatch(i, err) {
  816. if (err)
  817. return Promise.reject(err);
  818. if (i <= index)
  819. return Promise.reject(new Error("next() called multiple times"));
  820. index = i;
  821. const fn = middleware[i];
  822. if (!fn)
  823. return Promise.resolve();
  824. try {
  825. return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
  826. } catch (err2) {
  827. return Promise.reject(err2);
  828. }
  829. }
  830. }
  831. class Live2DLoader {
  832. static load(context) {
  833. return runMiddlewares(this.middlewares, context).then(() => context.result);
  834. }
  835. }
  836. Live2DLoader.middlewares = [XHRLoader.loader];
  837. function createTexture(url2, options = {}) {
  838. var _a;
  839. const textureOptions = { resourceOptions: { crossorigin: options.crossOrigin } };
  840. if (Texture.fromURL) {
  841. return Texture.fromURL(url2, textureOptions).catch((e) => {
  842. if (e instanceof Error) {
  843. throw e;
  844. }
  845. const err = new Error("Texture loading error");
  846. err.event = e;
  847. throw err;
  848. });
  849. }
  850. textureOptions.resourceOptions.autoLoad = false;
  851. const texture = Texture.from(url2, textureOptions);
  852. if (texture.baseTexture.valid) {
  853. return Promise.resolve(texture);
  854. }
  855. const resource = texture.baseTexture.resource;
  856. (_a = resource._live2d_load) != null ? _a : resource._live2d_load = new Promise((resolve, reject) => {
  857. const errorHandler = (event) => {
  858. resource.source.removeEventListener("error", errorHandler);
  859. const err = new Error("Texture loading error");
  860. err.event = event;
  861. reject(err);
  862. };
  863. resource.source.addEventListener("error", errorHandler);
  864. resource.load().then(() => resolve(texture)).catch(errorHandler);
  865. });
  866. return resource._live2d_load;
  867. }
  868. const TAG = "Live2DFactory";
  869. const urlToJSON = (context, next) => __async(void 0, null, function* () {
  870. if (typeof context.source === "string") {
  871. const data = yield Live2DLoader.load({
  872. url: context.source,
  873. type: "json",
  874. target: context.live2dModel
  875. });
  876. data.url = context.source;
  877. context.source = data;
  878. context.live2dModel.emit("settingsJSONLoaded", data);
  879. }
  880. return next();
  881. });
  882. const jsonToSettings = (context, next) => __async(void 0, null, function* () {
  883. if (context.source instanceof ModelSettings) {
  884. context.settings = context.source;
  885. return next();
  886. } else if (typeof context.source === "object") {
  887. const runtime = Live2DFactory.findRuntime(context.source);
  888. if (runtime) {
  889. const settings = runtime.createModelSettings(context.source);
  890. context.settings = settings;
  891. context.live2dModel.emit("settingsLoaded", settings);
  892. return next();
  893. }
  894. }
  895. throw new TypeError("Unknown settings format.");
  896. });
  897. const waitUntilReady = (context, next) => {
  898. if (context.settings) {
  899. const runtime = Live2DFactory.findRuntime(context.settings);
  900. if (runtime) {
  901. return runtime.ready().then(next);
  902. }
  903. }
  904. return next();
  905. };
  906. const setupOptionals = (context, next) => __async(void 0, null, function* () {
  907. yield next();
  908. const internalModel = context.internalModel;
  909. if (internalModel) {
  910. const settings = context.settings;
  911. const runtime = Live2DFactory.findRuntime(settings);
  912. if (runtime) {
  913. const tasks = [];
  914. if (settings.pose) {
  915. tasks.push(Live2DLoader.load({
  916. settings,
  917. url: settings.pose,
  918. type: "json",
  919. target: internalModel
  920. }).then((data) => {
  921. internalModel.pose = runtime.createPose(internalModel.coreModel, data);
  922. context.live2dModel.emit("poseLoaded", internalModel.pose);
  923. }).catch((e) => {
  924. context.live2dModel.emit("poseLoadError", e);
  925. logger.warn(TAG, "Failed to load pose.", e);
  926. }));
  927. }
  928. if (settings.physics) {
  929. tasks.push(Live2DLoader.load({
  930. settings,
  931. url: settings.physics,
  932. type: "json",
  933. target: internalModel
  934. }).then((data) => {
  935. internalModel.physics = runtime.createPhysics(internalModel.coreModel, data);
  936. context.live2dModel.emit("physicsLoaded", internalModel.physics);
  937. }).catch((e) => {
  938. context.live2dModel.emit("physicsLoadError", e);
  939. logger.warn(TAG, "Failed to load physics.", e);
  940. }));
  941. }
  942. if (tasks.length) {
  943. yield Promise.all(tasks);
  944. }
  945. }
  946. }
  947. });
  948. const setupEssentials = (context, next) => __async(void 0, null, function* () {
  949. if (context.settings) {
  950. const live2DModel = context.live2dModel;
  951. const textureLoadings = context.settings.textures.map((tex) => {
  952. const url2 = context.settings.resolveURL(tex);
  953. return createTexture(url2, { crossOrigin: context.options.crossOrigin });
  954. });
  955. yield next();
  956. if (context.internalModel) {
  957. live2DModel.internalModel = context.internalModel;
  958. live2DModel.emit("modelLoaded", context.internalModel);
  959. } else {
  960. throw new TypeError("Missing internal model.");
  961. }
  962. live2DModel.textures = yield Promise.all(textureLoadings);
  963. live2DModel.emit("textureLoaded", live2DModel.textures);
  964. } else {
  965. throw new TypeError("Missing settings.");
  966. }
  967. });
  968. const createInternalModel = (context, next) => __async(void 0, null, function* () {
  969. const settings = context.settings;
  970. if (settings instanceof ModelSettings) {
  971. const runtime = Live2DFactory.findRuntime(settings);
  972. if (!runtime) {
  973. throw new TypeError("Unknown model settings.");
  974. }
  975. const modelData = yield Live2DLoader.load({
  976. settings,
  977. url: settings.moc,
  978. type: "arraybuffer",
  979. target: context.live2dModel
  980. });
  981. if (!runtime.isValidMoc(modelData)) {
  982. throw new Error("Invalid moc data");
  983. }
  984. const coreModel = runtime.createCoreModel(modelData);
  985. context.internalModel = runtime.createInternalModel(coreModel, settings, context.options);
  986. return next();
  987. }
  988. throw new TypeError("Missing settings.");
  989. });
  990. const _Live2DFactory = class {
  991. static registerRuntime(runtime) {
  992. _Live2DFactory.runtimes.push(runtime);
  993. _Live2DFactory.runtimes.sort((a, b) => b.version - a.version);
  994. }
  995. static findRuntime(source) {
  996. for (const runtime of _Live2DFactory.runtimes) {
  997. if (runtime.test(source)) {
  998. return runtime;
  999. }
  1000. }
  1001. }
  1002. static setupLive2DModel(live2dModel, source, options) {
  1003. return __async(this, null, function* () {
  1004. const textureLoaded = new Promise((resolve) => live2dModel.once("textureLoaded", resolve));
  1005. const modelLoaded = new Promise((resolve) => live2dModel.once("modelLoaded", resolve));
  1006. const readyEventEmitted = Promise.all([textureLoaded, modelLoaded]).then(() => live2dModel.emit("ready"));
  1007. yield runMiddlewares(_Live2DFactory.live2DModelMiddlewares, {
  1008. live2dModel,
  1009. source,
  1010. options: options || {}
  1011. });
  1012. yield readyEventEmitted;
  1013. live2dModel.emit("load");
  1014. });
  1015. }
  1016. static loadMotion(motionManager, group, index) {
  1017. var _a, _b;
  1018. const handleError = (e) => motionManager.emit("motionLoadError", group, index, e);
  1019. try {
  1020. const definition = (_a = motionManager.definitions[group]) == null ? void 0 : _a[index];
  1021. if (!definition) {
  1022. return Promise.resolve(void 0);
  1023. }
  1024. if (!motionManager.listeners("destroy").includes(_Live2DFactory.releaseTasks)) {
  1025. motionManager.once("destroy", _Live2DFactory.releaseTasks);
  1026. }
  1027. let tasks = _Live2DFactory.motionTasksMap.get(motionManager);
  1028. if (!tasks) {
  1029. tasks = {};
  1030. _Live2DFactory.motionTasksMap.set(motionManager, tasks);
  1031. }
  1032. let taskGroup = tasks[group];
  1033. if (!taskGroup) {
  1034. taskGroup = [];
  1035. tasks[group] = taskGroup;
  1036. }
  1037. const path = motionManager.getMotionFile(definition);
  1038. (_b = taskGroup[index]) != null ? _b : taskGroup[index] = Live2DLoader.load({
  1039. url: path,
  1040. settings: motionManager.settings,
  1041. type: motionManager.motionDataType,
  1042. target: motionManager
  1043. }).then((data) => {
  1044. var _a2;
  1045. const taskGroup2 = (_a2 = _Live2DFactory.motionTasksMap.get(motionManager)) == null ? void 0 : _a2[group];
  1046. if (taskGroup2) {
  1047. delete taskGroup2[index];
  1048. }
  1049. const motion = motionManager.createMotion(data, group, definition);
  1050. motionManager.emit("motionLoaded", group, index, motion);
  1051. return motion;
  1052. }).catch((e) => {
  1053. logger.warn(motionManager.tag, `Failed to load motion: ${path}
  1054. `, e);
  1055. handleError(e);
  1056. });
  1057. return taskGroup[index];
  1058. } catch (e) {
  1059. logger.warn(motionManager.tag, `Failed to load motion at "${group}"[${index}]
  1060. `, e);
  1061. handleError(e);
  1062. }
  1063. return Promise.resolve(void 0);
  1064. }
  1065. static loadExpression(expressionManager, index) {
  1066. var _a;
  1067. const handleError = (e) => expressionManager.emit("expressionLoadError", index, e);
  1068. try {
  1069. const definition = expressionManager.definitions[index];
  1070. if (!definition) {
  1071. return Promise.resolve(void 0);
  1072. }
  1073. if (!expressionManager.listeners("destroy").includes(_Live2DFactory.releaseTasks)) {
  1074. expressionManager.once("destroy", _Live2DFactory.releaseTasks);
  1075. }
  1076. let tasks = _Live2DFactory.expressionTasksMap.get(expressionManager);
  1077. if (!tasks) {
  1078. tasks = [];
  1079. _Live2DFactory.expressionTasksMap.set(expressionManager, tasks);
  1080. }
  1081. const path = expressionManager.getExpressionFile(definition);
  1082. (_a = tasks[index]) != null ? _a : tasks[index] = Live2DLoader.load({
  1083. url: path,
  1084. settings: expressionManager.settings,
  1085. type: "json",
  1086. target: expressionManager
  1087. }).then((data) => {
  1088. const tasks2 = _Live2DFactory.expressionTasksMap.get(expressionManager);
  1089. if (tasks2) {
  1090. delete tasks2[index];
  1091. }
  1092. const expression = expressionManager.createExpression(data, definition);
  1093. expressionManager.emit("expressionLoaded", index, expression);
  1094. return expression;
  1095. }).catch((e) => {
  1096. logger.warn(expressionManager.tag, `Failed to load expression: ${path}
  1097. `, e);
  1098. handleError(e);
  1099. });
  1100. return tasks[index];
  1101. } catch (e) {
  1102. logger.warn(expressionManager.tag, `Failed to load expression at [${index}]
  1103. `, e);
  1104. handleError(e);
  1105. }
  1106. return Promise.resolve(void 0);
  1107. }
  1108. static releaseTasks() {
  1109. if (this instanceof MotionManager) {
  1110. _Live2DFactory.motionTasksMap.delete(this);
  1111. } else {
  1112. _Live2DFactory.expressionTasksMap.delete(this);
  1113. }
  1114. }
  1115. };
  1116. let Live2DFactory = _Live2DFactory;
  1117. Live2DFactory.runtimes = [];
  1118. Live2DFactory.urlToJSON = urlToJSON;
  1119. Live2DFactory.jsonToSettings = jsonToSettings;
  1120. Live2DFactory.waitUntilReady = waitUntilReady;
  1121. Live2DFactory.setupOptionals = setupOptionals;
  1122. Live2DFactory.setupEssentials = setupEssentials;
  1123. Live2DFactory.createInternalModel = createInternalModel;
  1124. Live2DFactory.live2DModelMiddlewares = [
  1125. urlToJSON,
  1126. jsonToSettings,
  1127. waitUntilReady,
  1128. setupOptionals,
  1129. setupEssentials,
  1130. createInternalModel
  1131. ];
  1132. Live2DFactory.motionTasksMap = /* @__PURE__ */ new WeakMap();
  1133. Live2DFactory.expressionTasksMap = /* @__PURE__ */ new WeakMap();
  1134. MotionManager.prototype["_loadMotion"] = function(group, index) {
  1135. return Live2DFactory.loadMotion(this, group, index);
  1136. };
  1137. ExpressionManager.prototype["_loadExpression"] = function(index) {
  1138. return Live2DFactory.loadExpression(this, index);
  1139. };
  1140. class InteractionMixin {
  1141. constructor() {
  1142. this._autoInteract = false;
  1143. }
  1144. get autoInteract() {
  1145. return this._autoInteract;
  1146. }
  1147. set autoInteract(autoInteract) {
  1148. if (autoInteract !== this._autoInteract) {
  1149. if (autoInteract) {
  1150. this.on("pointertap", onTap, this);
  1151. } else {
  1152. this.off("pointertap", onTap, this);
  1153. }
  1154. this._autoInteract = autoInteract;
  1155. }
  1156. }
  1157. registerInteraction(manager) {
  1158. if (manager !== this.interactionManager) {
  1159. this.unregisterInteraction();
  1160. if (this._autoInteract && manager) {
  1161. this.interactionManager = manager;
  1162. manager.on("pointermove", onPointerMove, this);
  1163. }
  1164. }
  1165. }
  1166. unregisterInteraction() {
  1167. var _a;
  1168. if (this.interactionManager) {
  1169. (_a = this.interactionManager) == null ? void 0 : _a.off("pointermove", onPointerMove, this);
  1170. this.interactionManager = void 0;
  1171. }
  1172. }
  1173. }
  1174. function onTap(event) {
  1175. this.tap(event.data.global.x, event.data.global.y);
  1176. }
  1177. function onPointerMove(event) {
  1178. this.focus(event.data.global.x, event.data.global.y);
  1179. }
  1180. class Live2DTransform extends Transform {
  1181. }
  1182. const tempPoint = new Point();
  1183. const tempMatrix = new Matrix();
  1184. let tickerRef;
  1185. class Live2DModel extends Container {
  1186. constructor(options) {
  1187. super();
  1188. this.tag = "Live2DModel(uninitialized)";
  1189. this.textures = [];
  1190. this.transform = new Live2DTransform();
  1191. this.anchor = new ObservablePoint(this.onAnchorChange, this, 0, 0);
  1192. this.glContextID = -1;
  1193. this.elapsedTime = performance.now();
  1194. this.deltaTime = 0;
  1195. this._autoUpdate = false;
  1196. this.once("modelLoaded", () => this.init(options));
  1197. }
  1198. static from(source, options) {
  1199. const model = new this(options);
  1200. return Live2DFactory.setupLive2DModel(model, source, options).then(() => model);
  1201. }
  1202. static fromSync(source, options) {
  1203. const model = new this(options);
  1204. Live2DFactory.setupLive2DModel(model, source, options).then(options == null ? void 0 : options.onLoad).catch(options == null ? void 0 : options.onError);
  1205. return model;
  1206. }
  1207. static registerTicker(tickerClass) {
  1208. tickerRef = tickerClass;
  1209. }
  1210. get autoUpdate() {
  1211. return this._autoUpdate;
  1212. }
  1213. set autoUpdate(autoUpdate) {
  1214. var _a;
  1215. tickerRef || (tickerRef = (_a = window.PIXI) == null ? void 0 : _a.Ticker);
  1216. if (autoUpdate) {
  1217. if (!this._destroyed) {
  1218. if (tickerRef) {
  1219. tickerRef.shared.add(this.onTickerUpdate, this);
  1220. this._autoUpdate = true;
  1221. } else {
  1222. logger.warn(this.tag, "No Ticker registered, please call Live2DModel.registerTicker(Ticker).");
  1223. }
  1224. }
  1225. } else {
  1226. tickerRef == null ? void 0 : tickerRef.shared.remove(this.onTickerUpdate, this);
  1227. this._autoUpdate = false;
  1228. }
  1229. }
  1230. init(options) {
  1231. this.tag = `Live2DModel(${this.internalModel.settings.name})`;
  1232. const _options = Object.assign({
  1233. autoUpdate: true,
  1234. autoInteract: true
  1235. }, options);
  1236. if (_options.autoInteract) {
  1237. this.interactive = true;
  1238. }
  1239. this.autoInteract = _options.autoInteract;
  1240. this.autoUpdate = _options.autoUpdate;
  1241. }
  1242. onAnchorChange() {
  1243. this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height);
  1244. }
  1245. motion(group, index, priority) {
  1246. return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority);
  1247. }
  1248. expression(id) {
  1249. if (this.internalModel.motionManager.expressionManager) {
  1250. return id === void 0 ? this.internalModel.motionManager.expressionManager.setRandomExpression() : this.internalModel.motionManager.expressionManager.setExpression(id);
  1251. }
  1252. return Promise.resolve(false);
  1253. }
  1254. focus(x, y, instant = false) {
  1255. tempPoint.x = x;
  1256. tempPoint.y = y;
  1257. this.toModelPosition(tempPoint, tempPoint, true);
  1258. let tx = tempPoint.x / this.internalModel.originalWidth * 2 - 1;
  1259. let ty = tempPoint.y / this.internalModel.originalHeight * 2 - 1;
  1260. let radian = Math.atan2(ty, tx);
  1261. this.internalModel.focusController.focus(Math.cos(radian), -Math.sin(radian), instant);
  1262. }
  1263. tap(x, y) {
  1264. const hitAreaNames = this.hitTest(x, y);
  1265. if (hitAreaNames.length) {
  1266. logger.log(this.tag, `Hit`, hitAreaNames);
  1267. this.emit("hit", hitAreaNames);
  1268. }
  1269. }
  1270. hitTest(x, y) {
  1271. tempPoint.x = x;
  1272. tempPoint.y = y;
  1273. this.toModelPosition(tempPoint, tempPoint);
  1274. return this.internalModel.hitTest(tempPoint.x, tempPoint.y);
  1275. }
  1276. toModelPosition(position, result = position.clone(), skipUpdate) {
  1277. if (!skipUpdate) {
  1278. this._recursivePostUpdateTransform();
  1279. if (!this.parent) {
  1280. this.parent = this._tempDisplayObjectParent;
  1281. this.displayObjectUpdateTransform();
  1282. this.parent = null;
  1283. } else {
  1284. this.displayObjectUpdateTransform();
  1285. }
  1286. }
  1287. this.transform.worldTransform.applyInverse(position, result);
  1288. this.internalModel.localTransform.applyInverse(result, result);
  1289. return result;
  1290. }
  1291. containsPoint(point) {
  1292. return this.getBounds(true).contains(point.x, point.y);
  1293. }
  1294. _calculateBounds() {
  1295. this._bounds.addFrame(this.transform, 0, 0, this.internalModel.width, this.internalModel.height);
  1296. }
  1297. onTickerUpdate() {
  1298. this.update(tickerRef.shared.deltaMS);
  1299. }
  1300. update(dt) {
  1301. this.deltaTime += dt;
  1302. this.elapsedTime += dt;
  1303. }
  1304. _render(renderer) {
  1305. this.registerInteraction(renderer.plugins.interaction);
  1306. renderer.batch.reset();
  1307. renderer.geometry.reset();
  1308. renderer.shader.reset();
  1309. renderer.state.reset();
  1310. let shouldUpdateTexture = false;
  1311. if (this.glContextID !== renderer.CONTEXT_UID) {
  1312. this.glContextID = renderer.CONTEXT_UID;
  1313. this.internalModel.updateWebGLContext(renderer.gl, this.glContextID);
  1314. shouldUpdateTexture = true;
  1315. }
  1316. for (let i = 0; i < this.textures.length; i++) {
  1317. const texture = this.textures[i];
  1318. if (!texture.valid) {
  1319. continue;
  1320. }
  1321. if (shouldUpdateTexture || !texture.baseTexture._glTextures[this.glContextID]) {
  1322. renderer.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL, this.internalModel.textureFlipY);
  1323. renderer.texture.bind(texture.baseTexture, 0);
  1324. }
  1325. this.internalModel.bindTexture(i, texture.baseTexture._glTextures[this.glContextID].texture);
  1326. texture.baseTexture.touched = renderer.textureGC.count;
  1327. }
  1328. const viewport = renderer.framebuffer.viewport;
  1329. this.internalModel.viewport = [viewport.x, viewport.y, viewport.width, viewport.height];
  1330. if (this.deltaTime) {
  1331. this.internalModel.update(this.deltaTime, this.elapsedTime);
  1332. this.deltaTime = 0;
  1333. }
  1334. const internalTransform = tempMatrix.copyFrom(renderer.globalUniforms.uniforms.projectionMatrix).append(this.worldTransform);
  1335. this.internalModel.updateTransform(internalTransform);
  1336. this.internalModel.draw(renderer.gl);
  1337. renderer.state.reset();
  1338. renderer.texture.reset();
  1339. }
  1340. destroy(options) {
  1341. this.emit("destroy");
  1342. this.autoUpdate = false;
  1343. this.unregisterInteraction();
  1344. if (options == null ? void 0 : options.texture) {
  1345. this.textures.forEach((texture) => texture.destroy(options.baseTexture));
  1346. }
  1347. this.internalModel.destroy();
  1348. super.destroy(options);
  1349. }
  1350. }
  1351. applyMixins(Live2DModel, [InteractionMixin]);
  1352. const _FileLoader = class {
  1353. static resolveURL(settingsURL, filePath) {
  1354. var _a;
  1355. const resolved = (_a = _FileLoader.filesMap[settingsURL]) == null ? void 0 : _a[filePath];
  1356. if (resolved === void 0) {
  1357. throw new Error("Cannot find this file from uploaded files: " + filePath);
  1358. }
  1359. return resolved;
  1360. }
  1361. static upload(files, settings) {
  1362. return __async(this, null, function* () {
  1363. const fileMap = {};
  1364. for (const definedFile of settings.getDefinedFiles()) {
  1365. const actualPath = decodeURI(url.resolve(settings.url, definedFile));
  1366. const actualFile = files.find((file) => file.webkitRelativePath === actualPath);
  1367. if (actualFile) {
  1368. fileMap[definedFile] = URL.createObjectURL(actualFile);
  1369. }
  1370. }
  1371. _FileLoader.filesMap[settings._objectURL] = fileMap;
  1372. });
  1373. }
  1374. static createSettings(files) {
  1375. return __async(this, null, function* () {
  1376. const settingsFile = files.find((file) => file.name.endsWith("model.json") || file.name.endsWith("model3.json"));
  1377. if (!settingsFile) {
  1378. throw new TypeError("Settings file not found");
  1379. }
  1380. const settingsText = yield _FileLoader.readText(settingsFile);
  1381. const settingsJSON = JSON.parse(settingsText);
  1382. settingsJSON.url = settingsFile.webkitRelativePath;
  1383. const runtime = Live2DFactory.findRuntime(settingsJSON);
  1384. if (!runtime) {
  1385. throw new Error("Unknown settings JSON");
  1386. }
  1387. const settings = runtime.createModelSettings(settingsJSON);
  1388. settings._objectURL = URL.createObjectURL(settingsFile);
  1389. return settings;
  1390. });
  1391. }
  1392. static readText(file) {
  1393. return __async(this, null, function* () {
  1394. return new Promise((resolve, reject) => {
  1395. const reader = new FileReader();
  1396. reader.onload = () => resolve(reader.result);
  1397. reader.onerror = reject;
  1398. reader.readAsText(file, "utf8");
  1399. });
  1400. });
  1401. }
  1402. };
  1403. let FileLoader = _FileLoader;
  1404. FileLoader.filesMap = {};
  1405. FileLoader.factory = (context, next) => __async(void 0, null, function* () {
  1406. if (Array.isArray(context.source) && context.source[0] instanceof File) {
  1407. const files = context.source;
  1408. let settings = files.settings;
  1409. if (!settings) {
  1410. settings = yield _FileLoader.createSettings(files);
  1411. } else if (!settings._objectURL) {
  1412. throw new Error('"_objectURL" must be specified in ModelSettings');
  1413. }
  1414. settings.validateFiles(files.map((file) => encodeURI(file.webkitRelativePath)));
  1415. yield _FileLoader.upload(files, settings);
  1416. settings.resolveURL = function(url2) {
  1417. return _FileLoader.resolveURL(this._objectURL, url2);
  1418. };
  1419. context.source = settings;
  1420. context.live2dModel.once("modelLoaded", (internalModel) => {
  1421. internalModel.once("destroy", function() {
  1422. const objectURL = this.settings._objectURL;
  1423. URL.revokeObjectURL(objectURL);
  1424. if (_FileLoader.filesMap[objectURL]) {
  1425. for (const resourceObjectURL of Object.values(_FileLoader.filesMap[objectURL])) {
  1426. URL.revokeObjectURL(resourceObjectURL);
  1427. }
  1428. }
  1429. delete _FileLoader.filesMap[objectURL];
  1430. });
  1431. });
  1432. }
  1433. return next();
  1434. });
  1435. Live2DFactory.live2DModelMiddlewares.unshift(FileLoader.factory);
  1436. const _ZipLoader = class {
  1437. static unzip(reader, settings) {
  1438. return __async(this, null, function* () {
  1439. const filePaths = yield _ZipLoader.getFilePaths(reader);
  1440. const requiredFilePaths = [];
  1441. for (const definedFile of settings.getDefinedFiles()) {
  1442. const actualPath = decodeURI(url.resolve(settings.url, definedFile));
  1443. if (filePaths.includes(actualPath)) {
  1444. requiredFilePaths.push(actualPath);
  1445. }
  1446. }
  1447. const files = yield _ZipLoader.getFiles(reader, requiredFilePaths);
  1448. for (let i = 0; i < files.length; i++) {
  1449. const path = requiredFilePaths[i];
  1450. const file = files[i];
  1451. Object.defineProperty(file, "webkitRelativePath", {
  1452. value: path
  1453. });
  1454. }
  1455. return files;
  1456. });
  1457. }
  1458. static createSettings(reader) {
  1459. return __async(this, null, function* () {
  1460. const filePaths = yield _ZipLoader.getFilePaths(reader);
  1461. const settingsFilePath = filePaths.find((path) => path.endsWith("model.json") || path.endsWith("model3.json"));
  1462. if (!settingsFilePath) {
  1463. throw new Error("Settings file not found");
  1464. }
  1465. const settingsText = yield _ZipLoader.readText(reader, settingsFilePath);
  1466. if (!settingsText) {
  1467. throw new Error("Empty settings file: " + settingsFilePath);
  1468. }
  1469. const settingsJSON = JSON.parse(settingsText);
  1470. settingsJSON.url = settingsFilePath;
  1471. const runtime = Live2DFactory.findRuntime(settingsJSON);
  1472. if (!runtime) {
  1473. throw new Error("Unknown settings JSON");
  1474. }
  1475. return runtime.createModelSettings(settingsJSON);
  1476. });
  1477. }
  1478. static zipReader(data, url2) {
  1479. return __async(this, null, function* () {
  1480. throw new Error("Not implemented");
  1481. });
  1482. }
  1483. static getFilePaths(reader) {
  1484. return __async(this, null, function* () {
  1485. throw new Error("Not implemented");
  1486. });
  1487. }
  1488. static getFiles(reader, paths) {
  1489. return __async(this, null, function* () {
  1490. throw new Error("Not implemented");
  1491. });
  1492. }
  1493. static readText(reader, path) {
  1494. return __async(this, null, function* () {
  1495. throw new Error("Not implemented");
  1496. });
  1497. }
  1498. static releaseReader(reader) {
  1499. }
  1500. };
  1501. let ZipLoader = _ZipLoader;
  1502. ZipLoader.ZIP_PROTOCOL = "zip://";
  1503. ZipLoader.uid = 0;
  1504. ZipLoader.factory = (context, next) => __async(void 0, null, function* () {
  1505. const source = context.source;
  1506. let sourceURL;
  1507. let zipBlob;
  1508. let settings;
  1509. if (typeof source === "string" && (source.endsWith(".zip") || source.startsWith(_ZipLoader.ZIP_PROTOCOL))) {
  1510. if (source.startsWith(_ZipLoader.ZIP_PROTOCOL)) {
  1511. sourceURL = source.slice(_ZipLoader.ZIP_PROTOCOL.length);
  1512. } else {
  1513. sourceURL = source;
  1514. }
  1515. zipBlob = yield Live2DLoader.load({
  1516. url: sourceURL,
  1517. type: "blob",
  1518. target: context.live2dModel
  1519. });
  1520. } else if (Array.isArray(source) && source.length === 1 && source[0] instanceof File && source[0].name.endsWith(".zip")) {
  1521. zipBlob = source[0];
  1522. sourceURL = URL.createObjectURL(zipBlob);
  1523. settings = source.settings;
  1524. }
  1525. if (zipBlob) {
  1526. if (!zipBlob.size) {
  1527. throw new Error("Empty zip file");
  1528. }
  1529. const reader = yield _ZipLoader.zipReader(zipBlob, sourceURL);
  1530. if (!settings) {
  1531. settings = yield _ZipLoader.createSettings(reader);
  1532. }
  1533. settings._objectURL = _ZipLoader.ZIP_PROTOCOL + _ZipLoader.uid + "/" + settings.url;
  1534. const files = yield _ZipLoader.unzip(reader, settings);
  1535. files.settings = settings;
  1536. context.source = files;
  1537. if (sourceURL.startsWith("blob:")) {
  1538. context.live2dModel.once("modelLoaded", (internalModel) => {
  1539. internalModel.once("destroy", function() {
  1540. URL.revokeObjectURL(sourceURL);
  1541. });
  1542. });
  1543. }
  1544. _ZipLoader.releaseReader(reader);
  1545. }
  1546. return next();
  1547. });
  1548. Live2DFactory.live2DModelMiddlewares.unshift(ZipLoader.factory);
  1549. if (!window.Live2D) {
  1550. throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");
  1551. }
  1552. const originalUpdateParam = Live2DMotion.prototype.updateParam;
  1553. Live2DMotion.prototype.updateParam = function(model, entry) {
  1554. originalUpdateParam.call(this, model, entry);
  1555. if (entry.isFinished() && this.onFinishHandler) {
  1556. this.onFinishHandler(this);
  1557. delete this.onFinishHandler;
  1558. }
  1559. };
  1560. class Live2DExpression extends AMotion {
  1561. constructor(json) {
  1562. super();
  1563. this.params = [];
  1564. this.setFadeIn(json.fade_in > 0 ? json.fade_in : config.expressionFadingDuration);
  1565. this.setFadeOut(json.fade_out > 0 ? json.fade_out : config.expressionFadingDuration);
  1566. if (Array.isArray(json.params)) {
  1567. json.params.forEach((param) => {
  1568. const calc = param.calc || "add";
  1569. if (calc === "add") {
  1570. const defaultValue = param.def || 0;
  1571. param.val -= defaultValue;
  1572. } else if (calc === "mult") {
  1573. const defaultValue = param.def || 1;
  1574. param.val /= defaultValue;
  1575. }
  1576. this.params.push({
  1577. calc,
  1578. val: param.val,
  1579. id: param.id
  1580. });
  1581. });
  1582. }
  1583. }
  1584. updateParamExe(model, time, weight, motionQueueEnt) {
  1585. this.params.forEach((param) => {
  1586. model.setParamFloat(param.id, param.val * weight);
  1587. });
  1588. }
  1589. }
  1590. class Cubism2ExpressionManager extends ExpressionManager {
  1591. constructor(settings, options) {
  1592. var _a;
  1593. super(settings, options);
  1594. this.queueManager = new MotionQueueManager();
  1595. this.definitions = (_a = this.settings.expressions) != null ? _a : [];
  1596. this.init();
  1597. }
  1598. isFinished() {
  1599. return this.queueManager.isFinished();
  1600. }
  1601. getExpressionIndex(name) {
  1602. return this.definitions.findIndex((def) => def.name === name);
  1603. }
  1604. getExpressionFile(definition) {
  1605. return definition.file;
  1606. }
  1607. createExpression(data, definition) {
  1608. return new Live2DExpression(data);
  1609. }
  1610. _setExpression(motion) {
  1611. return this.queueManager.startMotion(motion);
  1612. }
  1613. stopAllExpressions() {
  1614. this.queueManager.stopAllMotions();
  1615. }
  1616. updateParameters(model, dt) {
  1617. return this.queueManager.updateParam(model);
  1618. }
  1619. }
  1620. class Cubism2MotionManager extends MotionManager {
  1621. constructor(settings, options) {
  1622. super(settings, options);
  1623. this.groups = { idle: "idle" };
  1624. this.motionDataType = "arraybuffer";
  1625. this.queueManager = new MotionQueueManager();
  1626. this.definitions = this.settings.motions;
  1627. this.init(options);
  1628. }
  1629. init(options) {
  1630. super.init(options);
  1631. if (this.settings.expressions) {
  1632. this.expressionManager = new Cubism2ExpressionManager(this.settings, options);
  1633. }
  1634. }
  1635. isFinished() {
  1636. return this.queueManager.isFinished();
  1637. }
  1638. createMotion(data, group, definition) {
  1639. const motion = Live2DMotion.loadMotion(data);
  1640. const defaultFadingDuration = group === this.groups.idle ? config.idleMotionFadingDuration : config.motionFadingDuration;
  1641. motion.setFadeIn(definition.fade_in > 0 ? definition.fade_in : defaultFadingDuration);
  1642. motion.setFadeOut(definition.fade_out > 0 ? definition.fade_out : defaultFadingDuration);
  1643. return motion;
  1644. }
  1645. getMotionFile(definition) {
  1646. return definition.file;
  1647. }
  1648. getMotionName(definition) {
  1649. return definition.file;
  1650. }
  1651. getSoundFile(definition) {
  1652. return definition.sound;
  1653. }
  1654. _startMotion(motion, onFinish) {
  1655. motion.onFinishHandler = onFinish;
  1656. this.queueManager.stopAllMotions();
  1657. return this.queueManager.startMotion(motion);
  1658. }
  1659. _stopAllMotions() {
  1660. this.queueManager.stopAllMotions();
  1661. }
  1662. updateParameters(model, now) {
  1663. return this.queueManager.updateParam(model);
  1664. }
  1665. destroy() {
  1666. super.destroy();
  1667. this.queueManager = void 0;
  1668. }
  1669. }
  1670. class Live2DEyeBlink {
  1671. constructor(coreModel) {
  1672. this.coreModel = coreModel;
  1673. this.blinkInterval = 4e3;
  1674. this.closingDuration = 100;
  1675. this.closedDuration = 50;
  1676. this.openingDuration = 150;
  1677. this.eyeState = 0;
  1678. this.eyeParamValue = 1;
  1679. this.closedTimer = 0;
  1680. this.nextBlinkTimeLeft = this.blinkInterval;
  1681. this.leftParam = coreModel.getParamIndex("PARAM_EYE_L_OPEN");
  1682. this.rightParam = coreModel.getParamIndex("PARAM_EYE_R_OPEN");
  1683. }
  1684. setEyeParams(value) {
  1685. this.eyeParamValue = clamp(value, 0, 1);
  1686. this.coreModel.setParamFloat(this.leftParam, this.eyeParamValue);
  1687. this.coreModel.setParamFloat(this.rightParam, this.eyeParamValue);
  1688. }
  1689. update(dt) {
  1690. switch (this.eyeState) {
  1691. case 0:
  1692. this.nextBlinkTimeLeft -= dt;
  1693. if (this.nextBlinkTimeLeft < 0) {
  1694. this.eyeState = 1;
  1695. this.nextBlinkTimeLeft = this.blinkInterval + this.closingDuration + this.closedDuration + this.openingDuration + rand(0, 2e3);
  1696. }
  1697. break;
  1698. case 1:
  1699. this.setEyeParams(this.eyeParamValue + dt / this.closingDuration);
  1700. if (this.eyeParamValue <= 0) {
  1701. this.eyeState = 2;
  1702. this.closedTimer = 0;
  1703. }
  1704. break;
  1705. case 2:
  1706. this.closedTimer += dt;
  1707. if (this.closedTimer >= this.closedDuration) {
  1708. this.eyeState = 3;
  1709. }
  1710. break;
  1711. case 3:
  1712. this.setEyeParams(this.eyeParamValue + dt / this.openingDuration);
  1713. if (this.eyeParamValue >= 1) {
  1714. this.eyeState = 0;
  1715. }
  1716. }
  1717. }
  1718. }
  1719. const tempMatrixArray = new Float32Array([
  1720. 1,
  1721. 0,
  1722. 0,
  1723. 0,
  1724. 0,
  1725. 1,
  1726. 0,
  1727. 0,
  1728. 0,
  1729. 0,
  1730. 1,
  1731. 0,
  1732. 0,
  1733. 0,
  1734. 0,
  1735. 1
  1736. ]);
  1737. class Cubism2InternalModel extends InternalModel {
  1738. constructor(coreModel, settings, options) {
  1739. super();
  1740. this.textureFlipY = true;
  1741. this.drawDataCount = 0;
  1742. this.disableCulling = false;
  1743. this.coreModel = coreModel;
  1744. this.settings = settings;
  1745. this.motionManager = new Cubism2MotionManager(settings, options);
  1746. this.eyeBlink = new Live2DEyeBlink(coreModel);
  1747. this.eyeballXParamIndex = coreModel.getParamIndex("PARAM_EYE_BALL_X");
  1748. this.eyeballYParamIndex = coreModel.getParamIndex("PARAM_EYE_BALL_Y");
  1749. this.angleXParamIndex = coreModel.getParamIndex("PARAM_ANGLE_X");
  1750. this.angleYParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Y");
  1751. this.angleZParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Z");
  1752. this.bodyAngleXParamIndex = coreModel.getParamIndex("PARAM_BODY_ANGLE_X");
  1753. this.breathParamIndex = coreModel.getParamIndex("PARAM_BREATH");
  1754. this.init();
  1755. }
  1756. init() {
  1757. super.init();
  1758. if (this.settings.initParams) {
  1759. this.settings.initParams.forEach(({ id, value }) => this.coreModel.setParamFloat(id, value));
  1760. }
  1761. if (this.settings.initOpacities) {
  1762. this.settings.initOpacities.forEach(({ id, value }) => this.coreModel.setPartsOpacity(id, value));
  1763. }
  1764. this.coreModel.saveParam();
  1765. const arr = this.coreModel.getModelContext()._$aS;
  1766. if (arr == null ? void 0 : arr.length) {
  1767. this.drawDataCount = arr.length;
  1768. }
  1769. let culling = this.coreModel.drawParamWebGL.culling;
  1770. Object.defineProperty(this.coreModel.drawParamWebGL, "culling", {
  1771. set: (v) => culling = v,
  1772. get: () => this.disableCulling ? false : culling
  1773. });
  1774. const clipManager = this.coreModel.getModelContext().clipManager;
  1775. const originalSetupClip = clipManager.setupClip;
  1776. clipManager.setupClip = (modelContext, drawParam) => {
  1777. originalSetupClip.call(clipManager, modelContext, drawParam);
  1778. drawParam.gl.viewport(...this.viewport);
  1779. };
  1780. }
  1781. getSize() {
  1782. return [this.coreModel.getCanvasWidth(), this.coreModel.getCanvasHeight()];
  1783. }
  1784. getLayout() {
  1785. const layout = {};
  1786. if (this.settings.layout) {
  1787. for (const key of Object.keys(this.settings.layout)) {
  1788. let commonKey = key;
  1789. if (key === "center_x") {
  1790. commonKey = "centerX";
  1791. } else if (key === "center_y") {
  1792. commonKey = "centerY";
  1793. }
  1794. layout[commonKey] = this.settings.layout[key];
  1795. }
  1796. }
  1797. return layout;
  1798. }
  1799. updateWebGLContext(gl, glContextID) {
  1800. const drawParamWebGL = this.coreModel.drawParamWebGL;
  1801. drawParamWebGL.firstDraw = true;
  1802. drawParamWebGL.setGL(gl);
  1803. drawParamWebGL.glno = glContextID;
  1804. for (const prop in drawParamWebGL) {
  1805. if (drawParamWebGL.hasOwnProperty(prop) && drawParamWebGL[prop] instanceof WebGLBuffer) {
  1806. drawParamWebGL[prop] = null;
  1807. }
  1808. }
  1809. const clipManager = this.coreModel.getModelContext().clipManager;
  1810. clipManager.curFrameNo = glContextID;
  1811. const framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  1812. clipManager.getMaskRenderTexture();
  1813. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1814. }
  1815. bindTexture(index, texture) {
  1816. this.coreModel.setTexture(index, texture);
  1817. }
  1818. getHitAreaDefs() {
  1819. var _a;
  1820. return ((_a = this.settings.hitAreas) == null ? void 0 : _a.map((hitArea) => ({
  1821. id: hitArea.id,
  1822. name: hitArea.name,
  1823. index: this.coreModel.getDrawDataIndex(hitArea.id)
  1824. }))) || [];
  1825. }
  1826. getDrawableIDs() {
  1827. const modelContext = this.coreModel.getModelContext();
  1828. const ids = [];
  1829. for (let i = 0; i < this.drawDataCount; i++) {
  1830. const drawData = modelContext.getDrawData(i);
  1831. if (drawData) {
  1832. ids.push(drawData.getDrawDataID().id);
  1833. }
  1834. }
  1835. return ids;
  1836. }
  1837. getDrawableIndex(id) {
  1838. return this.coreModel.getDrawDataIndex(id);
  1839. }
  1840. getDrawableVertices(drawIndex) {
  1841. if (typeof drawIndex === "string") {
  1842. drawIndex = this.coreModel.getDrawDataIndex(drawIndex);
  1843. if (drawIndex === -1)
  1844. throw new TypeError("Unable to find drawable ID: " + drawIndex);
  1845. }
  1846. return this.coreModel.getTransformedPoints(drawIndex).slice();
  1847. }
  1848. update(dt, now) {
  1849. var _a, _b, _c, _d;
  1850. super.update(dt, now);
  1851. const model = this.coreModel;
  1852. this.emit("beforeMotionUpdate");
  1853. const motionUpdated = this.motionManager.update(this.coreModel, now);
  1854. this.emit("afterMotionUpdate");
  1855. model.saveParam();
  1856. (_a = this.motionManager.expressionManager) == null ? void 0 : _a.update(model, now);
  1857. if (!motionUpdated) {
  1858. (_b = this.eyeBlink) == null ? void 0 : _b.update(dt);
  1859. }
  1860. this.updateFocus();
  1861. this.updateNaturalMovements(dt, now);
  1862. (_c = this.physics) == null ? void 0 : _c.update(now);
  1863. (_d = this.pose) == null ? void 0 : _d.update(dt);
  1864. this.emit("beforeModelUpdate");
  1865. model.update();
  1866. model.loadParam();
  1867. }
  1868. updateFocus() {
  1869. this.coreModel.addToParamFloat(this.eyeballXParamIndex, this.focusController.x);
  1870. this.coreModel.addToParamFloat(this.eyeballYParamIndex, this.focusController.y);
  1871. this.coreModel.addToParamFloat(this.angleXParamIndex, this.focusController.x * 30);
  1872. this.coreModel.addToParamFloat(this.angleYParamIndex, this.focusController.y * 30);
  1873. this.coreModel.addToParamFloat(this.angleZParamIndex, this.focusController.x * this.focusController.y * -30);
  1874. this.coreModel.addToParamFloat(this.bodyAngleXParamIndex, this.focusController.x * 10);
  1875. }
  1876. updateNaturalMovements(dt, now) {
  1877. const t = now / 1e3 * 2 * Math.PI;
  1878. this.coreModel.addToParamFloat(this.angleXParamIndex, 15 * Math.sin(t / 6.5345) * 0.5);
  1879. this.coreModel.addToParamFloat(this.angleYParamIndex, 8 * Math.sin(t / 3.5345) * 0.5);
  1880. this.coreModel.addToParamFloat(this.angleZParamIndex, 10 * Math.sin(t / 5.5345) * 0.5);
  1881. this.coreModel.addToParamFloat(this.bodyAngleXParamIndex, 4 * Math.sin(t / 15.5345) * 0.5);
  1882. this.coreModel.setParamFloat(this.breathParamIndex, 0.5 + 0.5 * Math.sin(t / 3.2345));
  1883. }
  1884. draw(gl) {
  1885. const disableCulling = this.disableCulling;
  1886. if (gl.getParameter(gl.FRAMEBUFFER_BINDING)) {
  1887. this.disableCulling = true;
  1888. }
  1889. const matrix = this.drawingMatrix;
  1890. tempMatrixArray[0] = matrix.a;
  1891. tempMatrixArray[1] = matrix.b;
  1892. tempMatrixArray[4] = matrix.c;
  1893. tempMatrixArray[5] = matrix.d;
  1894. tempMatrixArray[12] = matrix.tx;
  1895. tempMatrixArray[13] = matrix.ty;
  1896. this.coreModel.setMatrix(tempMatrixArray);
  1897. this.coreModel.draw();
  1898. this.disableCulling = disableCulling;
  1899. }
  1900. destroy() {
  1901. super.destroy();
  1902. this.coreModel = void 0;
  1903. }
  1904. }
  1905. class Cubism2ModelSettings extends ModelSettings {
  1906. constructor(json) {
  1907. super(json);
  1908. this.motions = {};
  1909. if (!Cubism2ModelSettings.isValidJSON(json)) {
  1910. throw new TypeError("Invalid JSON.");
  1911. }
  1912. this.moc = json.model;
  1913. copyArray("string", json, this, "textures", "textures");
  1914. this.copy(json);
  1915. }
  1916. static isValidJSON(json) {
  1917. var _a;
  1918. return !!json && typeof json.model === "string" && ((_a = json.textures) == null ? void 0 : _a.length) > 0 && json.textures.every((item) => typeof item === "string");
  1919. }
  1920. copy(json) {
  1921. copyProperty("string", json, this, "name", "name");
  1922. copyProperty("string", json, this, "pose", "pose");
  1923. copyProperty("string", json, this, "physics", "physics");
  1924. copyProperty("object", json, this, "layout", "layout");
  1925. copyProperty("object", json, this, "motions", "motions");
  1926. copyArray("object", json, this, "hit_areas", "hitAreas");
  1927. copyArray("object", json, this, "expressions", "expressions");
  1928. copyArray("object", json, this, "init_params", "initParams");
  1929. copyArray("object", json, this, "init_opacities", "initOpacities");
  1930. }
  1931. replaceFiles(replace) {
  1932. super.replaceFiles(replace);
  1933. for (const [group, motions] of Object.entries(this.motions)) {
  1934. for (let i = 0; i < motions.length; i++) {
  1935. motions[i].file = replace(motions[i].file, `motions.${group}[${i}].file`);
  1936. if (motions[i].sound !== void 0) {
  1937. motions[i].sound = replace(motions[i].sound, `motions.${group}[${i}].sound`);
  1938. }
  1939. }
  1940. }
  1941. if (this.expressions) {
  1942. for (let i = 0; i < this.expressions.length; i++) {
  1943. this.expressions[i].file = replace(this.expressions[i].file, `expressions[${i}].file`);
  1944. }
  1945. }
  1946. }
  1947. }
  1948. const SRC_TYPE_MAP = {
  1949. x: PhysicsHair.Src.SRC_TO_X,
  1950. y: PhysicsHair.Src.SRC_TO_Y,
  1951. angle: PhysicsHair.Src.SRC_TO_G_ANGLE
  1952. };
  1953. const TARGET_TYPE_MAP = {
  1954. x: PhysicsHair.Src.SRC_TO_X,
  1955. y: PhysicsHair.Src.SRC_TO_Y,
  1956. angle: PhysicsHair.Src.SRC_TO_G_ANGLE
  1957. };
  1958. class Live2DPhysics {
  1959. constructor(coreModel, json) {
  1960. this.coreModel = coreModel;
  1961. this.physicsHairs = [];
  1962. if (json.physics_hair) {
  1963. this.physicsHairs = json.physics_hair.map((definition) => {
  1964. const physicsHair = new PhysicsHair();
  1965. physicsHair.setup(definition.setup.length, definition.setup.regist, definition.setup.mass);
  1966. definition.src.forEach(({ id, ptype, scale, weight }) => {
  1967. const type = SRC_TYPE_MAP[ptype];
  1968. if (type) {
  1969. physicsHair.addSrcParam(type, id, scale, weight);
  1970. }
  1971. });
  1972. definition.targets.forEach(({ id, ptype, scale, weight }) => {
  1973. const type = TARGET_TYPE_MAP[ptype];
  1974. if (type) {
  1975. physicsHair.addTargetParam(type, id, scale, weight);
  1976. }
  1977. });
  1978. return physicsHair;
  1979. });
  1980. }
  1981. }
  1982. update(elapsed) {
  1983. this.physicsHairs.forEach((physicsHair) => physicsHair.update(this.coreModel, elapsed));
  1984. }
  1985. }
  1986. class Live2DPartsParam {
  1987. constructor(id) {
  1988. this.id = id;
  1989. this.paramIndex = -1;
  1990. this.partsIndex = -1;
  1991. this.link = [];
  1992. }
  1993. initIndex(model) {
  1994. this.paramIndex = model.getParamIndex("VISIBLE:" + this.id);
  1995. this.partsIndex = model.getPartsDataIndex(PartsDataID.getID(this.id));
  1996. model.setParamFloat(this.paramIndex, 1);
  1997. }
  1998. }
  1999. class Live2DPose {
  2000. constructor(coreModel, json) {
  2001. this.coreModel = coreModel;
  2002. this.opacityAnimDuration = 500;
  2003. this.partsGroups = [];
  2004. if (json.parts_visible) {
  2005. this.partsGroups = json.parts_visible.map(({ group }) => group.map(({ id, link }) => {
  2006. const parts = new Live2DPartsParam(id);
  2007. if (link) {
  2008. parts.link = link.map((l) => new Live2DPartsParam(l));
  2009. }
  2010. return parts;
  2011. }));
  2012. this.init();
  2013. }
  2014. }
  2015. init() {
  2016. this.partsGroups.forEach((group) => {
  2017. group.forEach((parts) => {
  2018. parts.initIndex(this.coreModel);
  2019. if (parts.paramIndex >= 0) {
  2020. const visible = this.coreModel.getParamFloat(parts.paramIndex) !== 0;
  2021. this.coreModel.setPartsOpacity(parts.partsIndex, visible ? 1 : 0);
  2022. this.coreModel.setParamFloat(parts.paramIndex, visible ? 1 : 0);
  2023. if (parts.link.length > 0) {
  2024. parts.link.forEach((p) => p.initIndex(this.coreModel));
  2025. }
  2026. }
  2027. });
  2028. });
  2029. }
  2030. normalizePartsOpacityGroup(partsGroup, dt) {
  2031. const model = this.coreModel;
  2032. const phi = 0.5;
  2033. const maxBackOpacity = 0.15;
  2034. let visibleOpacity = 1;
  2035. let visibleIndex = partsGroup.findIndex(({ paramIndex, partsIndex }) => partsIndex >= 0 && model.getParamFloat(paramIndex) !== 0);
  2036. if (visibleIndex >= 0) {
  2037. const originalOpacity = model.getPartsOpacity(partsGroup[visibleIndex].partsIndex);
  2038. visibleOpacity = clamp(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
  2039. } else {
  2040. visibleIndex = 0;
  2041. visibleOpacity = 1;
  2042. }
  2043. partsGroup.forEach(({ partsIndex }, index) => {
  2044. if (partsIndex >= 0) {
  2045. if (visibleIndex == index) {
  2046. model.setPartsOpacity(partsIndex, visibleOpacity);
  2047. } else {
  2048. let opacity = model.getPartsOpacity(partsIndex);
  2049. let a1;
  2050. if (visibleOpacity < phi) {
  2051. a1 = visibleOpacity * (phi - 1) / phi + 1;
  2052. } else {
  2053. a1 = (1 - visibleOpacity) * phi / (1 - phi);
  2054. }
  2055. let backOp = (1 - a1) * (1 - visibleOpacity);
  2056. if (backOp > maxBackOpacity) {
  2057. a1 = 1 - maxBackOpacity / (1 - visibleOpacity);
  2058. }
  2059. if (opacity > a1) {
  2060. opacity = a1;
  2061. }
  2062. model.setPartsOpacity(partsIndex, opacity);
  2063. }
  2064. }
  2065. });
  2066. }
  2067. copyOpacity(partsGroup) {
  2068. const model = this.coreModel;
  2069. partsGroup.forEach(({ partsIndex, link }) => {
  2070. if (partsIndex >= 0 && link) {
  2071. const opacity = model.getPartsOpacity(partsIndex);
  2072. link.forEach(({ partsIndex: partsIndex2 }) => {
  2073. if (partsIndex2 >= 0) {
  2074. model.setPartsOpacity(partsIndex2, opacity);
  2075. }
  2076. });
  2077. }
  2078. });
  2079. }
  2080. update(dt) {
  2081. this.partsGroups.forEach((partGroup) => {
  2082. this.normalizePartsOpacityGroup(partGroup, dt);
  2083. this.copyOpacity(partGroup);
  2084. });
  2085. }
  2086. }
  2087. Live2DFactory.registerRuntime({
  2088. version: 2,
  2089. test(source) {
  2090. return source instanceof Cubism2ModelSettings || Cubism2ModelSettings.isValidJSON(source);
  2091. },
  2092. ready() {
  2093. return Promise.resolve();
  2094. },
  2095. isValidMoc(modelData) {
  2096. if (modelData.byteLength < 3) {
  2097. return false;
  2098. }
  2099. const view = new Int8Array(modelData, 0, 3);
  2100. return String.fromCharCode(...view) === "moc";
  2101. },
  2102. createModelSettings(json) {
  2103. return new Cubism2ModelSettings(json);
  2104. },
  2105. createCoreModel(data) {
  2106. const model = Live2DModelWebGL.loadModel(data);
  2107. const error = Live2D.getError();
  2108. if (error)
  2109. throw error;
  2110. return model;
  2111. },
  2112. createInternalModel(coreModel, settings, options) {
  2113. return new Cubism2InternalModel(coreModel, settings, options);
  2114. },
  2115. createPose(coreModel, data) {
  2116. return new Live2DPose(coreModel, data);
  2117. },
  2118. createPhysics(coreModel, data) {
  2119. return new Live2DPhysics(coreModel, data);
  2120. }
  2121. });
  2122. export { Cubism2ExpressionManager, Cubism2InternalModel, Cubism2ModelSettings, Cubism2MotionManager, ExpressionManager, FileLoader, FocusController, InteractionMixin, InternalModel, LOGICAL_HEIGHT, LOGICAL_WIDTH, Live2DExpression, Live2DEyeBlink, Live2DFactory, Live2DLoader, Live2DModel, Live2DPhysics, Live2DPose, Live2DTransform, ModelSettings, MotionManager, MotionPreloadStrategy, MotionPriority, MotionState, SoundManager, VERSION, XHRLoader, ZipLoader, applyMixins, clamp, config, copyArray, copyProperty, folderName, logger, rand, remove };