pixi-live2d-display_cubism4.js 204 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721
  1. import {
  2. Container,
  3. Matrix,
  4. ObservablePoint,
  5. Point,
  6. Texture,
  7. Transform,
  8. import_eventemitter3,
  9. url
  10. } from "./chunk-66BJ5UTJ.js";
  11. import "./chunk-DC5AMYBS.js";
  12. // node_modules/pixi-live2d-display/dist/cubism4.es.js
  13. var __pow = Math.pow;
  14. var __async = (__this, __arguments, generator) => {
  15. return new Promise((resolve, reject) => {
  16. var fulfilled = (value) => {
  17. try {
  18. step(generator.next(value));
  19. } catch (e) {
  20. reject(e);
  21. }
  22. };
  23. var rejected = (value) => {
  24. try {
  25. step(generator.throw(value));
  26. } catch (e) {
  27. reject(e);
  28. }
  29. };
  30. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  31. step((generator = generator.apply(__this, __arguments)).next());
  32. });
  33. };
  34. var CubismBreath = class _CubismBreath {
  35. constructor() {
  36. this._breathParameters = [];
  37. this._currentTime = 0;
  38. }
  39. static create() {
  40. return new _CubismBreath();
  41. }
  42. setParameters(breathParameters) {
  43. this._breathParameters = breathParameters;
  44. }
  45. getParameters() {
  46. return this._breathParameters;
  47. }
  48. updateParameters(model, deltaTimeSeconds) {
  49. this._currentTime += deltaTimeSeconds;
  50. const t = this._currentTime * 2 * 3.14159;
  51. for (let i = 0; i < this._breathParameters.length; ++i) {
  52. const data = this._breathParameters[i];
  53. model.addParameterValueById(data.parameterId, data.offset + data.peak * Math.sin(t / data.cycle), data.weight);
  54. }
  55. }
  56. };
  57. var BreathParameterData = class {
  58. constructor(parameterId, offset, peak, cycle, weight) {
  59. this.parameterId = parameterId == void 0 ? void 0 : parameterId;
  60. this.offset = offset == void 0 ? 0 : offset;
  61. this.peak = peak == void 0 ? 0 : peak;
  62. this.cycle = cycle == void 0 ? 0 : cycle;
  63. this.weight = weight == void 0 ? 0 : weight;
  64. }
  65. };
  66. var _CubismEyeBlink = class {
  67. static create(modelSetting) {
  68. return new _CubismEyeBlink(modelSetting);
  69. }
  70. setBlinkingInterval(blinkingInterval) {
  71. this._blinkingIntervalSeconds = blinkingInterval;
  72. }
  73. setBlinkingSetting(closing, closed, opening) {
  74. this._closingSeconds = closing;
  75. this._closedSeconds = closed;
  76. this._openingSeconds = opening;
  77. }
  78. setParameterIds(parameterIds) {
  79. this._parameterIds = parameterIds;
  80. }
  81. getParameterIds() {
  82. return this._parameterIds;
  83. }
  84. updateParameters(model, deltaTimeSeconds) {
  85. this._userTimeSeconds += deltaTimeSeconds;
  86. let parameterValue;
  87. let t = 0;
  88. switch (this._blinkingState) {
  89. case EyeState.EyeState_Closing:
  90. t = (this._userTimeSeconds - this._stateStartTimeSeconds) / this._closingSeconds;
  91. if (t >= 1) {
  92. t = 1;
  93. this._blinkingState = EyeState.EyeState_Closed;
  94. this._stateStartTimeSeconds = this._userTimeSeconds;
  95. }
  96. parameterValue = 1 - t;
  97. break;
  98. case EyeState.EyeState_Closed:
  99. t = (this._userTimeSeconds - this._stateStartTimeSeconds) / this._closedSeconds;
  100. if (t >= 1) {
  101. this._blinkingState = EyeState.EyeState_Opening;
  102. this._stateStartTimeSeconds = this._userTimeSeconds;
  103. }
  104. parameterValue = 0;
  105. break;
  106. case EyeState.EyeState_Opening:
  107. t = (this._userTimeSeconds - this._stateStartTimeSeconds) / this._openingSeconds;
  108. if (t >= 1) {
  109. t = 1;
  110. this._blinkingState = EyeState.EyeState_Interval;
  111. this._nextBlinkingTime = this.determinNextBlinkingTiming();
  112. }
  113. parameterValue = t;
  114. break;
  115. case EyeState.EyeState_Interval:
  116. if (this._nextBlinkingTime < this._userTimeSeconds) {
  117. this._blinkingState = EyeState.EyeState_Closing;
  118. this._stateStartTimeSeconds = this._userTimeSeconds;
  119. }
  120. parameterValue = 1;
  121. break;
  122. case EyeState.EyeState_First:
  123. default:
  124. this._blinkingState = EyeState.EyeState_Interval;
  125. this._nextBlinkingTime = this.determinNextBlinkingTiming();
  126. parameterValue = 1;
  127. break;
  128. }
  129. if (!_CubismEyeBlink.CloseIfZero) {
  130. parameterValue = -parameterValue;
  131. }
  132. for (let i = 0; i < this._parameterIds.length; ++i) {
  133. model.setParameterValueById(this._parameterIds[i], parameterValue);
  134. }
  135. }
  136. constructor(modelSetting) {
  137. var _a, _b;
  138. this._blinkingState = EyeState.EyeState_First;
  139. this._nextBlinkingTime = 0;
  140. this._stateStartTimeSeconds = 0;
  141. this._blinkingIntervalSeconds = 4;
  142. this._closingSeconds = 0.1;
  143. this._closedSeconds = 0.05;
  144. this._openingSeconds = 0.15;
  145. this._userTimeSeconds = 0;
  146. this._parameterIds = [];
  147. if (modelSetting == null) {
  148. return;
  149. }
  150. this._parameterIds = (_b = (_a = modelSetting.getEyeBlinkParameters()) == null ? void 0 : _a.slice()) != null ? _b : this._parameterIds;
  151. }
  152. determinNextBlinkingTiming() {
  153. const r = Math.random();
  154. return this._userTimeSeconds + r * (2 * this._blinkingIntervalSeconds - 1);
  155. }
  156. };
  157. var CubismEyeBlink = _CubismEyeBlink;
  158. CubismEyeBlink.CloseIfZero = true;
  159. var EyeState = ((EyeState2) => {
  160. EyeState2[EyeState2["EyeState_First"] = 0] = "EyeState_First";
  161. EyeState2[EyeState2["EyeState_Interval"] = 1] = "EyeState_Interval";
  162. EyeState2[EyeState2["EyeState_Closing"] = 2] = "EyeState_Closing";
  163. EyeState2[EyeState2["EyeState_Closed"] = 3] = "EyeState_Closed";
  164. EyeState2[EyeState2["EyeState_Opening"] = 4] = "EyeState_Opening";
  165. return EyeState2;
  166. })(EyeState || {});
  167. var Epsilon = 1e-3;
  168. var DefaultFadeInSeconds = 0.5;
  169. var CubismPose = class _CubismPose {
  170. static create(pose3json) {
  171. const ret = new _CubismPose();
  172. if (typeof pose3json.FadeInTime === "number") {
  173. ret._fadeTimeSeconds = pose3json.FadeInTime;
  174. if (ret._fadeTimeSeconds <= 0) {
  175. ret._fadeTimeSeconds = DefaultFadeInSeconds;
  176. }
  177. }
  178. const poseListInfo = pose3json.Groups;
  179. const poseCount = poseListInfo.length;
  180. for (let poseIndex = 0; poseIndex < poseCount; ++poseIndex) {
  181. const idListInfo = poseListInfo[poseIndex];
  182. const idCount = idListInfo.length;
  183. let groupCount = 0;
  184. for (let groupIndex = 0; groupIndex < idCount; ++groupIndex) {
  185. const partInfo = idListInfo[groupIndex];
  186. const partData = new PartData();
  187. partData.partId = partInfo.Id;
  188. const linkListInfo = partInfo.Link;
  189. if (linkListInfo) {
  190. const linkCount = linkListInfo.length;
  191. for (let linkIndex = 0; linkIndex < linkCount; ++linkIndex) {
  192. const linkPart = new PartData();
  193. linkPart.partId = linkListInfo[linkIndex];
  194. partData.link.push(linkPart);
  195. }
  196. }
  197. ret._partGroups.push(partData);
  198. ++groupCount;
  199. }
  200. ret._partGroupCounts.push(groupCount);
  201. }
  202. return ret;
  203. }
  204. updateParameters(model, deltaTimeSeconds) {
  205. if (model != this._lastModel) {
  206. this.reset(model);
  207. }
  208. this._lastModel = model;
  209. if (deltaTimeSeconds < 0) {
  210. deltaTimeSeconds = 0;
  211. }
  212. let beginIndex = 0;
  213. for (let i = 0; i < this._partGroupCounts.length; i++) {
  214. const partGroupCount = this._partGroupCounts[i];
  215. this.doFade(model, deltaTimeSeconds, beginIndex, partGroupCount);
  216. beginIndex += partGroupCount;
  217. }
  218. this.copyPartOpacities(model);
  219. }
  220. reset(model) {
  221. let beginIndex = 0;
  222. for (let i = 0; i < this._partGroupCounts.length; ++i) {
  223. const groupCount = this._partGroupCounts[i];
  224. for (let j = beginIndex; j < beginIndex + groupCount; ++j) {
  225. this._partGroups[j].initialize(model);
  226. const partsIndex = this._partGroups[j].partIndex;
  227. const paramIndex = this._partGroups[j].parameterIndex;
  228. if (partsIndex < 0) {
  229. continue;
  230. }
  231. model.setPartOpacityByIndex(partsIndex, j == beginIndex ? 1 : 0);
  232. model.setParameterValueByIndex(paramIndex, j == beginIndex ? 1 : 0);
  233. for (let k = 0; k < this._partGroups[j].link.length; ++k) {
  234. this._partGroups[j].link[k].initialize(model);
  235. }
  236. }
  237. beginIndex += groupCount;
  238. }
  239. }
  240. copyPartOpacities(model) {
  241. for (let groupIndex = 0; groupIndex < this._partGroups.length; ++groupIndex) {
  242. const partData = this._partGroups[groupIndex];
  243. if (partData.link.length == 0) {
  244. continue;
  245. }
  246. const partIndex = this._partGroups[groupIndex].partIndex;
  247. const opacity = model.getPartOpacityByIndex(partIndex);
  248. for (let linkIndex = 0; linkIndex < partData.link.length; ++linkIndex) {
  249. const linkPart = partData.link[linkIndex];
  250. const linkPartIndex = linkPart.partIndex;
  251. if (linkPartIndex < 0) {
  252. continue;
  253. }
  254. model.setPartOpacityByIndex(linkPartIndex, opacity);
  255. }
  256. }
  257. }
  258. doFade(model, deltaTimeSeconds, beginIndex, partGroupCount) {
  259. let visiblePartIndex = -1;
  260. let newOpacity = 1;
  261. const phi = 0.5;
  262. const backOpacityThreshold = 0.15;
  263. for (let i = beginIndex; i < beginIndex + partGroupCount; ++i) {
  264. const partIndex = this._partGroups[i].partIndex;
  265. const paramIndex = this._partGroups[i].parameterIndex;
  266. if (model.getParameterValueByIndex(paramIndex) > Epsilon) {
  267. if (visiblePartIndex >= 0) {
  268. break;
  269. }
  270. visiblePartIndex = i;
  271. newOpacity = model.getPartOpacityByIndex(partIndex);
  272. newOpacity += deltaTimeSeconds / this._fadeTimeSeconds;
  273. if (newOpacity > 1) {
  274. newOpacity = 1;
  275. }
  276. }
  277. }
  278. if (visiblePartIndex < 0) {
  279. visiblePartIndex = 0;
  280. newOpacity = 1;
  281. }
  282. for (let i = beginIndex; i < beginIndex + partGroupCount; ++i) {
  283. const partsIndex = this._partGroups[i].partIndex;
  284. if (visiblePartIndex == i) {
  285. model.setPartOpacityByIndex(partsIndex, newOpacity);
  286. } else {
  287. let opacity = model.getPartOpacityByIndex(partsIndex);
  288. let a1;
  289. if (newOpacity < phi) {
  290. a1 = newOpacity * (phi - 1) / phi + 1;
  291. } else {
  292. a1 = (1 - newOpacity) * phi / (1 - phi);
  293. }
  294. const backOpacity = (1 - a1) * (1 - newOpacity);
  295. if (backOpacity > backOpacityThreshold) {
  296. a1 = 1 - backOpacityThreshold / (1 - newOpacity);
  297. }
  298. if (opacity > a1) {
  299. opacity = a1;
  300. }
  301. model.setPartOpacityByIndex(partsIndex, opacity);
  302. }
  303. }
  304. }
  305. constructor() {
  306. this._fadeTimeSeconds = DefaultFadeInSeconds;
  307. this._lastModel = void 0;
  308. this._partGroups = [];
  309. this._partGroupCounts = [];
  310. }
  311. };
  312. var PartData = class _PartData {
  313. constructor(v) {
  314. this.parameterIndex = 0;
  315. this.partIndex = 0;
  316. this.partId = "";
  317. this.link = [];
  318. if (v != void 0) {
  319. this.assignment(v);
  320. }
  321. }
  322. assignment(v) {
  323. this.partId = v.partId;
  324. this.link = v.link.map((link) => link.clone());
  325. return this;
  326. }
  327. initialize(model) {
  328. this.parameterIndex = model.getParameterIndex(this.partId);
  329. this.partIndex = model.getPartIndex(this.partId);
  330. model.setParameterValueByIndex(this.parameterIndex, 1);
  331. }
  332. clone() {
  333. const clonePartData = new _PartData();
  334. clonePartData.partId = this.partId;
  335. clonePartData.parameterIndex = this.parameterIndex;
  336. clonePartData.partIndex = this.partIndex;
  337. clonePartData.link = this.link.map((link) => link.clone());
  338. return clonePartData;
  339. }
  340. };
  341. var CubismVector2 = class _CubismVector2 {
  342. constructor(x, y) {
  343. this.x = x || 0;
  344. this.y = y || 0;
  345. }
  346. add(vector2) {
  347. const ret = new _CubismVector2(0, 0);
  348. ret.x = this.x + vector2.x;
  349. ret.y = this.y + vector2.y;
  350. return ret;
  351. }
  352. substract(vector2) {
  353. const ret = new _CubismVector2(0, 0);
  354. ret.x = this.x - vector2.x;
  355. ret.y = this.y - vector2.y;
  356. return ret;
  357. }
  358. multiply(vector2) {
  359. const ret = new _CubismVector2(0, 0);
  360. ret.x = this.x * vector2.x;
  361. ret.y = this.y * vector2.y;
  362. return ret;
  363. }
  364. multiplyByScaler(scalar) {
  365. return this.multiply(new _CubismVector2(scalar, scalar));
  366. }
  367. division(vector2) {
  368. const ret = new _CubismVector2(0, 0);
  369. ret.x = this.x / vector2.x;
  370. ret.y = this.y / vector2.y;
  371. return ret;
  372. }
  373. divisionByScalar(scalar) {
  374. return this.division(new _CubismVector2(scalar, scalar));
  375. }
  376. getLength() {
  377. return Math.sqrt(this.x * this.x + this.y * this.y);
  378. }
  379. getDistanceWith(a) {
  380. return Math.sqrt((this.x - a.x) * (this.x - a.x) + (this.y - a.y) * (this.y - a.y));
  381. }
  382. dot(a) {
  383. return this.x * a.x + this.y * a.y;
  384. }
  385. normalize() {
  386. const length = Math.pow(this.x * this.x + this.y * this.y, 0.5);
  387. this.x = this.x / length;
  388. this.y = this.y / length;
  389. }
  390. isEqual(rhs) {
  391. return this.x == rhs.x && this.y == rhs.y;
  392. }
  393. isNotEqual(rhs) {
  394. return !this.isEqual(rhs);
  395. }
  396. };
  397. var _CubismMath = class {
  398. static range(value, min, max) {
  399. if (value < min) {
  400. value = min;
  401. } else if (value > max) {
  402. value = max;
  403. }
  404. return value;
  405. }
  406. static sin(x) {
  407. return Math.sin(x);
  408. }
  409. static cos(x) {
  410. return Math.cos(x);
  411. }
  412. static abs(x) {
  413. return Math.abs(x);
  414. }
  415. static sqrt(x) {
  416. return Math.sqrt(x);
  417. }
  418. static cbrt(x) {
  419. if (x === 0) {
  420. return x;
  421. }
  422. let cx = x;
  423. const isNegativeNumber = cx < 0;
  424. if (isNegativeNumber) {
  425. cx = -cx;
  426. }
  427. let ret;
  428. if (cx === Infinity) {
  429. ret = Infinity;
  430. } else {
  431. ret = Math.exp(Math.log(cx) / 3);
  432. ret = (cx / (ret * ret) + 2 * ret) / 3;
  433. }
  434. return isNegativeNumber ? -ret : ret;
  435. }
  436. static getEasingSine(value) {
  437. if (value < 0) {
  438. return 0;
  439. } else if (value > 1) {
  440. return 1;
  441. }
  442. return 0.5 - 0.5 * this.cos(value * Math.PI);
  443. }
  444. static max(left, right) {
  445. return left > right ? left : right;
  446. }
  447. static min(left, right) {
  448. return left > right ? right : left;
  449. }
  450. static degreesToRadian(degrees) {
  451. return degrees / 180 * Math.PI;
  452. }
  453. static radianToDegrees(radian) {
  454. return radian * 180 / Math.PI;
  455. }
  456. static directionToRadian(from, to) {
  457. const q1 = Math.atan2(to.y, to.x);
  458. const q2 = Math.atan2(from.y, from.x);
  459. let ret = q1 - q2;
  460. while (ret < -Math.PI) {
  461. ret += Math.PI * 2;
  462. }
  463. while (ret > Math.PI) {
  464. ret -= Math.PI * 2;
  465. }
  466. return ret;
  467. }
  468. static directionToDegrees(from, to) {
  469. const radian = this.directionToRadian(from, to);
  470. let degree = this.radianToDegrees(radian);
  471. if (to.x - from.x > 0) {
  472. degree = -degree;
  473. }
  474. return degree;
  475. }
  476. static radianToDirection(totalAngle) {
  477. const ret = new CubismVector2();
  478. ret.x = this.sin(totalAngle);
  479. ret.y = this.cos(totalAngle);
  480. return ret;
  481. }
  482. static quadraticEquation(a, b, c) {
  483. if (this.abs(a) < _CubismMath.Epsilon) {
  484. if (this.abs(b) < _CubismMath.Epsilon) {
  485. return -c;
  486. }
  487. return -c / b;
  488. }
  489. return -(b + this.sqrt(b * b - 4 * a * c)) / (2 * a);
  490. }
  491. static cardanoAlgorithmForBezier(a, b, c, d) {
  492. if (this.sqrt(a) < _CubismMath.Epsilon) {
  493. return this.range(this.quadraticEquation(b, c, d), 0, 1);
  494. }
  495. const ba = b / a;
  496. const ca = c / a;
  497. const da = d / a;
  498. const p = (3 * ca - ba * ba) / 3;
  499. const p3 = p / 3;
  500. const q = (2 * ba * ba * ba - 9 * ba * ca + 27 * da) / 27;
  501. const q2 = q / 2;
  502. const discriminant = q2 * q2 + p3 * p3 * p3;
  503. const center = 0.5;
  504. const threshold = center + 0.01;
  505. if (discriminant < 0) {
  506. const mp3 = -p / 3;
  507. const mp33 = mp3 * mp3 * mp3;
  508. const r = this.sqrt(mp33);
  509. const t = -q / (2 * r);
  510. const cosphi = this.range(t, -1, 1);
  511. const phi = Math.acos(cosphi);
  512. const crtr = this.cbrt(r);
  513. const t1 = 2 * crtr;
  514. const root12 = t1 * this.cos(phi / 3) - ba / 3;
  515. if (this.abs(root12 - center) < threshold) {
  516. return this.range(root12, 0, 1);
  517. }
  518. const root2 = t1 * this.cos((phi + 2 * Math.PI) / 3) - ba / 3;
  519. if (this.abs(root2 - center) < threshold) {
  520. return this.range(root2, 0, 1);
  521. }
  522. const root3 = t1 * this.cos((phi + 4 * Math.PI) / 3) - ba / 3;
  523. return this.range(root3, 0, 1);
  524. }
  525. if (discriminant == 0) {
  526. let u12;
  527. if (q2 < 0) {
  528. u12 = this.cbrt(-q2);
  529. } else {
  530. u12 = -this.cbrt(q2);
  531. }
  532. const root12 = 2 * u12 - ba / 3;
  533. if (this.abs(root12 - center) < threshold) {
  534. return this.range(root12, 0, 1);
  535. }
  536. const root2 = -u12 - ba / 3;
  537. return this.range(root2, 0, 1);
  538. }
  539. const sd = this.sqrt(discriminant);
  540. const u1 = this.cbrt(sd - q2);
  541. const v1 = this.cbrt(sd + q2);
  542. const root1 = u1 - v1 - ba / 3;
  543. return this.range(root1, 0, 1);
  544. }
  545. constructor() {
  546. }
  547. };
  548. var CubismMath = _CubismMath;
  549. CubismMath.Epsilon = 1e-5;
  550. var CubismMatrix44 = class _CubismMatrix44 {
  551. constructor() {
  552. this._tr = new Float32Array(16);
  553. this.loadIdentity();
  554. }
  555. static multiply(a, b, dst) {
  556. const c = new Float32Array([
  557. 0,
  558. 0,
  559. 0,
  560. 0,
  561. 0,
  562. 0,
  563. 0,
  564. 0,
  565. 0,
  566. 0,
  567. 0,
  568. 0,
  569. 0,
  570. 0,
  571. 0,
  572. 0
  573. ]);
  574. const n = 4;
  575. for (let i = 0; i < n; ++i) {
  576. for (let j = 0; j < n; ++j) {
  577. for (let k = 0; k < n; ++k) {
  578. c[j + i * 4] += a[k + i * 4] * b[j + k * 4];
  579. }
  580. }
  581. }
  582. for (let i = 0; i < 16; ++i) {
  583. dst[i] = c[i];
  584. }
  585. }
  586. loadIdentity() {
  587. const c = new Float32Array([
  588. 1,
  589. 0,
  590. 0,
  591. 0,
  592. 0,
  593. 1,
  594. 0,
  595. 0,
  596. 0,
  597. 0,
  598. 1,
  599. 0,
  600. 0,
  601. 0,
  602. 0,
  603. 1
  604. ]);
  605. this.setMatrix(c);
  606. }
  607. setMatrix(tr) {
  608. for (let i = 0; i < 16; ++i) {
  609. this._tr[i] = tr[i];
  610. }
  611. }
  612. getArray() {
  613. return this._tr;
  614. }
  615. getScaleX() {
  616. return this._tr[0];
  617. }
  618. getScaleY() {
  619. return this._tr[5];
  620. }
  621. getTranslateX() {
  622. return this._tr[12];
  623. }
  624. getTranslateY() {
  625. return this._tr[13];
  626. }
  627. transformX(src) {
  628. return this._tr[0] * src + this._tr[12];
  629. }
  630. transformY(src) {
  631. return this._tr[5] * src + this._tr[13];
  632. }
  633. invertTransformX(src) {
  634. return (src - this._tr[12]) / this._tr[0];
  635. }
  636. invertTransformY(src) {
  637. return (src - this._tr[13]) / this._tr[5];
  638. }
  639. translateRelative(x, y) {
  640. const tr1 = new Float32Array([
  641. 1,
  642. 0,
  643. 0,
  644. 0,
  645. 0,
  646. 1,
  647. 0,
  648. 0,
  649. 0,
  650. 0,
  651. 1,
  652. 0,
  653. x,
  654. y,
  655. 0,
  656. 1
  657. ]);
  658. _CubismMatrix44.multiply(tr1, this._tr, this._tr);
  659. }
  660. translate(x, y) {
  661. this._tr[12] = x;
  662. this._tr[13] = y;
  663. }
  664. translateX(x) {
  665. this._tr[12] = x;
  666. }
  667. translateY(y) {
  668. this._tr[13] = y;
  669. }
  670. scaleRelative(x, y) {
  671. const tr1 = new Float32Array([
  672. x,
  673. 0,
  674. 0,
  675. 0,
  676. 0,
  677. y,
  678. 0,
  679. 0,
  680. 0,
  681. 0,
  682. 1,
  683. 0,
  684. 0,
  685. 0,
  686. 0,
  687. 1
  688. ]);
  689. _CubismMatrix44.multiply(tr1, this._tr, this._tr);
  690. }
  691. scale(x, y) {
  692. this._tr[0] = x;
  693. this._tr[5] = y;
  694. }
  695. multiplyByMatrix(m) {
  696. _CubismMatrix44.multiply(m.getArray(), this._tr, this._tr);
  697. }
  698. clone() {
  699. const cloneMatrix = new _CubismMatrix44();
  700. for (let i = 0; i < this._tr.length; i++) {
  701. cloneMatrix._tr[i] = this._tr[i];
  702. }
  703. return cloneMatrix;
  704. }
  705. };
  706. var CubismRenderer = class {
  707. initialize(model) {
  708. this._model = model;
  709. }
  710. drawModel() {
  711. if (this.getModel() == null)
  712. return;
  713. this.doDrawModel();
  714. }
  715. setMvpMatrix(matrix44) {
  716. this._mvpMatrix4x4.setMatrix(matrix44.getArray());
  717. }
  718. getMvpMatrix() {
  719. return this._mvpMatrix4x4;
  720. }
  721. setModelColor(red, green, blue, alpha) {
  722. if (red < 0) {
  723. red = 0;
  724. } else if (red > 1) {
  725. red = 1;
  726. }
  727. if (green < 0) {
  728. green = 0;
  729. } else if (green > 1) {
  730. green = 1;
  731. }
  732. if (blue < 0) {
  733. blue = 0;
  734. } else if (blue > 1) {
  735. blue = 1;
  736. }
  737. if (alpha < 0) {
  738. alpha = 0;
  739. } else if (alpha > 1) {
  740. alpha = 1;
  741. }
  742. this._modelColor.R = red;
  743. this._modelColor.G = green;
  744. this._modelColor.B = blue;
  745. this._modelColor.A = alpha;
  746. }
  747. getModelColor() {
  748. return Object.assign({}, this._modelColor);
  749. }
  750. setIsPremultipliedAlpha(enable) {
  751. this._isPremultipliedAlpha = enable;
  752. }
  753. isPremultipliedAlpha() {
  754. return this._isPremultipliedAlpha;
  755. }
  756. setIsCulling(culling) {
  757. this._isCulling = culling;
  758. }
  759. isCulling() {
  760. return this._isCulling;
  761. }
  762. setAnisotropy(n) {
  763. this._anisortopy = n;
  764. }
  765. getAnisotropy() {
  766. return this._anisortopy;
  767. }
  768. getModel() {
  769. return this._model;
  770. }
  771. constructor() {
  772. this._isCulling = false;
  773. this._isPremultipliedAlpha = false;
  774. this._anisortopy = 0;
  775. this._modelColor = new CubismTextureColor();
  776. this._mvpMatrix4x4 = new CubismMatrix44();
  777. this._mvpMatrix4x4.loadIdentity();
  778. }
  779. };
  780. var CubismBlendMode = ((CubismBlendMode2) => {
  781. CubismBlendMode2[CubismBlendMode2["CubismBlendMode_Normal"] = 0] = "CubismBlendMode_Normal";
  782. CubismBlendMode2[CubismBlendMode2["CubismBlendMode_Additive"] = 1] = "CubismBlendMode_Additive";
  783. CubismBlendMode2[CubismBlendMode2["CubismBlendMode_Multiplicative"] = 2] = "CubismBlendMode_Multiplicative";
  784. return CubismBlendMode2;
  785. })(CubismBlendMode || {});
  786. var CubismTextureColor = class {
  787. constructor() {
  788. this.R = 1;
  789. this.G = 1;
  790. this.B = 1;
  791. this.A = 1;
  792. }
  793. };
  794. var s_isStarted = false;
  795. var s_isInitialized = false;
  796. var s_option = void 0;
  797. var Constant = {
  798. vertexOffset: 0,
  799. vertexStep: 2
  800. };
  801. var CubismFramework = class {
  802. static startUp(option) {
  803. if (s_isStarted) {
  804. CubismLogInfo("CubismFramework.startUp() is already done.");
  805. return s_isStarted;
  806. }
  807. if (Live2DCubismCore._isStarted) {
  808. s_isStarted = true;
  809. return true;
  810. }
  811. Live2DCubismCore._isStarted = true;
  812. s_option = option;
  813. if (s_option) {
  814. Live2DCubismCore.Logging.csmSetLogFunction(s_option.logFunction);
  815. }
  816. s_isStarted = true;
  817. if (s_isStarted) {
  818. const version = Live2DCubismCore.Version.csmGetVersion();
  819. const major = (version & 4278190080) >> 24;
  820. const minor = (version & 16711680) >> 16;
  821. const patch = version & 65535;
  822. const versionNumber = version;
  823. CubismLogInfo(`Live2D Cubism Core version: {0}.{1}.{2} ({3})`, ("00" + major).slice(-2), ("00" + minor).slice(-2), ("0000" + patch).slice(-4), versionNumber);
  824. }
  825. CubismLogInfo("CubismFramework.startUp() is complete.");
  826. return s_isStarted;
  827. }
  828. static cleanUp() {
  829. s_isStarted = false;
  830. s_isInitialized = false;
  831. s_option = void 0;
  832. }
  833. static initialize() {
  834. if (!s_isStarted) {
  835. CubismLogWarning("CubismFramework is not started.");
  836. return;
  837. }
  838. if (s_isInitialized) {
  839. CubismLogWarning("CubismFramework.initialize() skipped, already initialized.");
  840. return;
  841. }
  842. s_isInitialized = true;
  843. CubismLogInfo("CubismFramework.initialize() is complete.");
  844. }
  845. static dispose() {
  846. if (!s_isStarted) {
  847. CubismLogWarning("CubismFramework is not started.");
  848. return;
  849. }
  850. if (!s_isInitialized) {
  851. CubismLogWarning("CubismFramework.dispose() skipped, not initialized.");
  852. return;
  853. }
  854. CubismRenderer.staticRelease();
  855. s_isInitialized = false;
  856. CubismLogInfo("CubismFramework.dispose() is complete.");
  857. }
  858. static isStarted() {
  859. return s_isStarted;
  860. }
  861. static isInitialized() {
  862. return s_isInitialized;
  863. }
  864. static coreLogFunction(message) {
  865. if (!Live2DCubismCore.Logging.csmGetLogFunction()) {
  866. return;
  867. }
  868. Live2DCubismCore.Logging.csmGetLogFunction()(message);
  869. }
  870. static getLoggingLevel() {
  871. if (s_option != null) {
  872. return s_option.loggingLevel;
  873. }
  874. return LogLevel.LogLevel_Off;
  875. }
  876. constructor() {
  877. }
  878. };
  879. var LogLevel = ((LogLevel2) => {
  880. LogLevel2[LogLevel2["LogLevel_Verbose"] = 0] = "LogLevel_Verbose";
  881. LogLevel2[LogLevel2["LogLevel_Debug"] = 1] = "LogLevel_Debug";
  882. LogLevel2[LogLevel2["LogLevel_Info"] = 2] = "LogLevel_Info";
  883. LogLevel2[LogLevel2["LogLevel_Warning"] = 3] = "LogLevel_Warning";
  884. LogLevel2[LogLevel2["LogLevel_Error"] = 4] = "LogLevel_Error";
  885. LogLevel2[LogLevel2["LogLevel_Off"] = 5] = "LogLevel_Off";
  886. return LogLevel2;
  887. })(LogLevel || {});
  888. var CSM_ASSERT = () => {
  889. };
  890. function CubismLogVerbose(fmt, ...args) {
  891. CubismDebug.print(LogLevel.LogLevel_Verbose, "[CSM][V]" + fmt + "\n", args);
  892. }
  893. function CubismLogDebug(fmt, ...args) {
  894. CubismDebug.print(LogLevel.LogLevel_Debug, "[CSM][D]" + fmt + "\n", args);
  895. }
  896. function CubismLogInfo(fmt, ...args) {
  897. CubismDebug.print(LogLevel.LogLevel_Info, "[CSM][I]" + fmt + "\n", args);
  898. }
  899. function CubismLogWarning(fmt, ...args) {
  900. CubismDebug.print(LogLevel.LogLevel_Warning, "[CSM][W]" + fmt + "\n", args);
  901. }
  902. function CubismLogError(fmt, ...args) {
  903. CubismDebug.print(LogLevel.LogLevel_Error, "[CSM][E]" + fmt + "\n", args);
  904. }
  905. var CubismDebug = class {
  906. static print(logLevel, format, args) {
  907. if (logLevel < CubismFramework.getLoggingLevel()) {
  908. return;
  909. }
  910. const logPrint = CubismFramework.coreLogFunction;
  911. if (!logPrint)
  912. return;
  913. const buffer = format.replace(/{(\d+)}/g, (m, k) => {
  914. return args[k];
  915. });
  916. logPrint(buffer);
  917. }
  918. static dumpBytes(logLevel, data, length) {
  919. for (let i = 0; i < length; i++) {
  920. if (i % 16 == 0 && i > 0)
  921. this.print(logLevel, "\n");
  922. else if (i % 8 == 0 && i > 0)
  923. this.print(logLevel, " ");
  924. this.print(logLevel, "{0} ", [data[i] & 255]);
  925. }
  926. this.print(logLevel, "\n");
  927. }
  928. constructor() {
  929. }
  930. };
  931. var CubismModel = class {
  932. update() {
  933. this._model.update();
  934. this._model.drawables.resetDynamicFlags();
  935. }
  936. getCanvasWidth() {
  937. if (this._model == null) {
  938. return 0;
  939. }
  940. return this._model.canvasinfo.CanvasWidth / this._model.canvasinfo.PixelsPerUnit;
  941. }
  942. getCanvasHeight() {
  943. if (this._model == null) {
  944. return 0;
  945. }
  946. return this._model.canvasinfo.CanvasHeight / this._model.canvasinfo.PixelsPerUnit;
  947. }
  948. saveParameters() {
  949. const parameterCount = this._model.parameters.count;
  950. const savedParameterCount = this._savedParameters.length;
  951. for (let i = 0; i < parameterCount; ++i) {
  952. if (i < savedParameterCount) {
  953. this._savedParameters[i] = this._parameterValues[i];
  954. } else {
  955. this._savedParameters.push(this._parameterValues[i]);
  956. }
  957. }
  958. }
  959. getModel() {
  960. return this._model;
  961. }
  962. getPartIndex(partId) {
  963. let partIndex;
  964. const partCount = this._model.parts.count;
  965. for (partIndex = 0; partIndex < partCount; ++partIndex) {
  966. if (partId == this._partIds[partIndex]) {
  967. return partIndex;
  968. }
  969. }
  970. if (partId in this._notExistPartId) {
  971. return this._notExistPartId[partId];
  972. }
  973. partIndex = partCount + this._notExistPartId.length;
  974. this._notExistPartId[partId] = partIndex;
  975. this._notExistPartOpacities[partIndex] = 0;
  976. return partIndex;
  977. }
  978. getPartCount() {
  979. return this._model.parts.count;
  980. }
  981. setPartOpacityByIndex(partIndex, opacity) {
  982. if (partIndex in this._notExistPartOpacities) {
  983. this._notExistPartOpacities[partIndex] = opacity;
  984. return;
  985. }
  986. CSM_ASSERT(0 <= partIndex && partIndex < this.getPartCount());
  987. this._partOpacities[partIndex] = opacity;
  988. }
  989. setPartOpacityById(partId, opacity) {
  990. const index = this.getPartIndex(partId);
  991. if (index < 0) {
  992. return;
  993. }
  994. this.setPartOpacityByIndex(index, opacity);
  995. }
  996. getPartOpacityByIndex(partIndex) {
  997. if (partIndex in this._notExistPartOpacities) {
  998. return this._notExistPartOpacities[partIndex];
  999. }
  1000. CSM_ASSERT(0 <= partIndex && partIndex < this.getPartCount());
  1001. return this._partOpacities[partIndex];
  1002. }
  1003. getPartOpacityById(partId) {
  1004. const index = this.getPartIndex(partId);
  1005. if (index < 0) {
  1006. return 0;
  1007. }
  1008. return this.getPartOpacityByIndex(index);
  1009. }
  1010. getParameterIndex(parameterId) {
  1011. let parameterIndex;
  1012. const idCount = this._model.parameters.count;
  1013. for (parameterIndex = 0; parameterIndex < idCount; ++parameterIndex) {
  1014. if (parameterId != this._parameterIds[parameterIndex]) {
  1015. continue;
  1016. }
  1017. return parameterIndex;
  1018. }
  1019. if (parameterId in this._notExistParameterId) {
  1020. return this._notExistParameterId[parameterId];
  1021. }
  1022. parameterIndex = this._model.parameters.count + Object.keys(this._notExistParameterId).length;
  1023. this._notExistParameterId[parameterId] = parameterIndex;
  1024. this._notExistParameterValues[parameterIndex] = 0;
  1025. return parameterIndex;
  1026. }
  1027. getParameterCount() {
  1028. return this._model.parameters.count;
  1029. }
  1030. getParameterMaximumValue(parameterIndex) {
  1031. return this._model.parameters.maximumValues[parameterIndex];
  1032. }
  1033. getParameterMinimumValue(parameterIndex) {
  1034. return this._model.parameters.minimumValues[parameterIndex];
  1035. }
  1036. getParameterDefaultValue(parameterIndex) {
  1037. return this._model.parameters.defaultValues[parameterIndex];
  1038. }
  1039. getParameterValueByIndex(parameterIndex) {
  1040. if (parameterIndex in this._notExistParameterValues) {
  1041. return this._notExistParameterValues[parameterIndex];
  1042. }
  1043. CSM_ASSERT(0 <= parameterIndex && parameterIndex < this.getParameterCount());
  1044. return this._parameterValues[parameterIndex];
  1045. }
  1046. getParameterValueById(parameterId) {
  1047. const parameterIndex = this.getParameterIndex(parameterId);
  1048. return this.getParameterValueByIndex(parameterIndex);
  1049. }
  1050. setParameterValueByIndex(parameterIndex, value, weight = 1) {
  1051. if (parameterIndex in this._notExistParameterValues) {
  1052. this._notExistParameterValues[parameterIndex] = weight == 1 ? value : this._notExistParameterValues[parameterIndex] * (1 - weight) + value * weight;
  1053. return;
  1054. }
  1055. CSM_ASSERT(0 <= parameterIndex && parameterIndex < this.getParameterCount());
  1056. if (this._model.parameters.maximumValues[parameterIndex] < value) {
  1057. value = this._model.parameters.maximumValues[parameterIndex];
  1058. }
  1059. if (this._model.parameters.minimumValues[parameterIndex] > value) {
  1060. value = this._model.parameters.minimumValues[parameterIndex];
  1061. }
  1062. this._parameterValues[parameterIndex] = weight == 1 ? value : this._parameterValues[parameterIndex] = this._parameterValues[parameterIndex] * (1 - weight) + value * weight;
  1063. }
  1064. setParameterValueById(parameterId, value, weight = 1) {
  1065. const index = this.getParameterIndex(parameterId);
  1066. this.setParameterValueByIndex(index, value, weight);
  1067. }
  1068. addParameterValueByIndex(parameterIndex, value, weight = 1) {
  1069. this.setParameterValueByIndex(parameterIndex, this.getParameterValueByIndex(parameterIndex) + value * weight);
  1070. }
  1071. addParameterValueById(parameterId, value, weight = 1) {
  1072. const index = this.getParameterIndex(parameterId);
  1073. this.addParameterValueByIndex(index, value, weight);
  1074. }
  1075. multiplyParameterValueById(parameterId, value, weight = 1) {
  1076. const index = this.getParameterIndex(parameterId);
  1077. this.multiplyParameterValueByIndex(index, value, weight);
  1078. }
  1079. multiplyParameterValueByIndex(parameterIndex, value, weight = 1) {
  1080. this.setParameterValueByIndex(parameterIndex, this.getParameterValueByIndex(parameterIndex) * (1 + (value - 1) * weight));
  1081. }
  1082. getDrawableIds() {
  1083. return this._drawableIds.slice();
  1084. }
  1085. getDrawableIndex(drawableId) {
  1086. const drawableCount = this._model.drawables.count;
  1087. for (let drawableIndex = 0; drawableIndex < drawableCount; ++drawableIndex) {
  1088. if (this._drawableIds[drawableIndex] == drawableId) {
  1089. return drawableIndex;
  1090. }
  1091. }
  1092. return -1;
  1093. }
  1094. getDrawableCount() {
  1095. return this._model.drawables.count;
  1096. }
  1097. getDrawableId(drawableIndex) {
  1098. return this._model.drawables.ids[drawableIndex];
  1099. }
  1100. getDrawableRenderOrders() {
  1101. return this._model.drawables.renderOrders;
  1102. }
  1103. getDrawableTextureIndices(drawableIndex) {
  1104. return this._model.drawables.textureIndices[drawableIndex];
  1105. }
  1106. getDrawableDynamicFlagVertexPositionsDidChange(drawableIndex) {
  1107. const dynamicFlags = this._model.drawables.dynamicFlags;
  1108. return Live2DCubismCore.Utils.hasVertexPositionsDidChangeBit(dynamicFlags[drawableIndex]);
  1109. }
  1110. getDrawableVertexIndexCount(drawableIndex) {
  1111. return this._model.drawables.indexCounts[drawableIndex];
  1112. }
  1113. getDrawableVertexCount(drawableIndex) {
  1114. return this._model.drawables.vertexCounts[drawableIndex];
  1115. }
  1116. getDrawableVertices(drawableIndex) {
  1117. return this.getDrawableVertexPositions(drawableIndex);
  1118. }
  1119. getDrawableVertexIndices(drawableIndex) {
  1120. return this._model.drawables.indices[drawableIndex];
  1121. }
  1122. getDrawableVertexPositions(drawableIndex) {
  1123. return this._model.drawables.vertexPositions[drawableIndex];
  1124. }
  1125. getDrawableVertexUvs(drawableIndex) {
  1126. return this._model.drawables.vertexUvs[drawableIndex];
  1127. }
  1128. getDrawableOpacity(drawableIndex) {
  1129. return this._model.drawables.opacities[drawableIndex];
  1130. }
  1131. getDrawableCulling(drawableIndex) {
  1132. const constantFlags = this._model.drawables.constantFlags;
  1133. return !Live2DCubismCore.Utils.hasIsDoubleSidedBit(constantFlags[drawableIndex]);
  1134. }
  1135. getDrawableBlendMode(drawableIndex) {
  1136. const constantFlags = this._model.drawables.constantFlags;
  1137. return Live2DCubismCore.Utils.hasBlendAdditiveBit(constantFlags[drawableIndex]) ? CubismBlendMode.CubismBlendMode_Additive : Live2DCubismCore.Utils.hasBlendMultiplicativeBit(constantFlags[drawableIndex]) ? CubismBlendMode.CubismBlendMode_Multiplicative : CubismBlendMode.CubismBlendMode_Normal;
  1138. }
  1139. getDrawableInvertedMaskBit(drawableIndex) {
  1140. const constantFlags = this._model.drawables.constantFlags;
  1141. return Live2DCubismCore.Utils.hasIsInvertedMaskBit(constantFlags[drawableIndex]);
  1142. }
  1143. getDrawableMasks() {
  1144. return this._model.drawables.masks;
  1145. }
  1146. getDrawableMaskCounts() {
  1147. return this._model.drawables.maskCounts;
  1148. }
  1149. isUsingMasking() {
  1150. for (let d = 0; d < this._model.drawables.count; ++d) {
  1151. if (this._model.drawables.maskCounts[d] <= 0) {
  1152. continue;
  1153. }
  1154. return true;
  1155. }
  1156. return false;
  1157. }
  1158. getDrawableDynamicFlagIsVisible(drawableIndex) {
  1159. const dynamicFlags = this._model.drawables.dynamicFlags;
  1160. return Live2DCubismCore.Utils.hasIsVisibleBit(dynamicFlags[drawableIndex]);
  1161. }
  1162. getDrawableDynamicFlagVisibilityDidChange(drawableIndex) {
  1163. const dynamicFlags = this._model.drawables.dynamicFlags;
  1164. return Live2DCubismCore.Utils.hasVisibilityDidChangeBit(dynamicFlags[drawableIndex]);
  1165. }
  1166. getDrawableDynamicFlagOpacityDidChange(drawableIndex) {
  1167. const dynamicFlags = this._model.drawables.dynamicFlags;
  1168. return Live2DCubismCore.Utils.hasOpacityDidChangeBit(dynamicFlags[drawableIndex]);
  1169. }
  1170. getDrawableDynamicFlagRenderOrderDidChange(drawableIndex) {
  1171. const dynamicFlags = this._model.drawables.dynamicFlags;
  1172. return Live2DCubismCore.Utils.hasRenderOrderDidChangeBit(dynamicFlags[drawableIndex]);
  1173. }
  1174. loadParameters() {
  1175. let parameterCount = this._model.parameters.count;
  1176. const savedParameterCount = this._savedParameters.length;
  1177. if (parameterCount > savedParameterCount) {
  1178. parameterCount = savedParameterCount;
  1179. }
  1180. for (let i = 0; i < parameterCount; ++i) {
  1181. this._parameterValues[i] = this._savedParameters[i];
  1182. }
  1183. }
  1184. initialize() {
  1185. this._parameterValues = this._model.parameters.values;
  1186. this._partOpacities = this._model.parts.opacities;
  1187. this._parameterMaximumValues = this._model.parameters.maximumValues;
  1188. this._parameterMinimumValues = this._model.parameters.minimumValues;
  1189. {
  1190. const parameterIds = this._model.parameters.ids;
  1191. const parameterCount = this._model.parameters.count;
  1192. for (let i = 0; i < parameterCount; ++i) {
  1193. this._parameterIds.push(parameterIds[i]);
  1194. }
  1195. }
  1196. {
  1197. const partIds = this._model.parts.ids;
  1198. const partCount = this._model.parts.count;
  1199. for (let i = 0; i < partCount; ++i) {
  1200. this._partIds.push(partIds[i]);
  1201. }
  1202. }
  1203. {
  1204. const drawableIds = this._model.drawables.ids;
  1205. const drawableCount = this._model.drawables.count;
  1206. for (let i = 0; i < drawableCount; ++i) {
  1207. this._drawableIds.push(drawableIds[i]);
  1208. }
  1209. }
  1210. }
  1211. constructor(model) {
  1212. this._model = model;
  1213. this._savedParameters = [];
  1214. this._parameterIds = [];
  1215. this._drawableIds = [];
  1216. this._partIds = [];
  1217. this._notExistPartId = {};
  1218. this._notExistParameterId = {};
  1219. this._notExistParameterValues = {};
  1220. this._notExistPartOpacities = {};
  1221. this.initialize();
  1222. }
  1223. release() {
  1224. this._model.release();
  1225. this._model = void 0;
  1226. }
  1227. };
  1228. var CubismMoc = class _CubismMoc {
  1229. static create(mocBytes) {
  1230. const moc = Live2DCubismCore.Moc.fromArrayBuffer(mocBytes);
  1231. if (moc) {
  1232. return new _CubismMoc(moc);
  1233. }
  1234. throw new Error("Unknown error");
  1235. }
  1236. createModel() {
  1237. let cubismModel;
  1238. const model = Live2DCubismCore.Model.fromMoc(this._moc);
  1239. if (model) {
  1240. cubismModel = new CubismModel(model);
  1241. ++this._modelCount;
  1242. return cubismModel;
  1243. }
  1244. throw new Error("Unknown error");
  1245. }
  1246. deleteModel(model) {
  1247. if (model != null) {
  1248. --this._modelCount;
  1249. }
  1250. }
  1251. constructor(moc) {
  1252. this._moc = moc;
  1253. this._modelCount = 0;
  1254. }
  1255. release() {
  1256. this._moc._release();
  1257. this._moc = void 0;
  1258. }
  1259. };
  1260. var CubismModelUserDataJson = class {
  1261. constructor(json, size) {
  1262. this._json = json;
  1263. }
  1264. release() {
  1265. this._json = void 0;
  1266. }
  1267. getUserDataCount() {
  1268. return this._json.Meta.UserDataCount;
  1269. }
  1270. getTotalUserDataSize() {
  1271. return this._json.Meta.TotalUserDataSize;
  1272. }
  1273. getUserDataTargetType(i) {
  1274. return this._json.UserData[i].Target;
  1275. }
  1276. getUserDataId(i) {
  1277. return this._json.UserData[i].Id;
  1278. }
  1279. getUserDataValue(i) {
  1280. return this._json.UserData[i].Value;
  1281. }
  1282. };
  1283. var ArtMesh = "ArtMesh";
  1284. var CubismModelUserData = class _CubismModelUserData {
  1285. static create(json, size) {
  1286. const ret = new _CubismModelUserData();
  1287. ret.parseUserData(json, size);
  1288. return ret;
  1289. }
  1290. getArtMeshUserDatas() {
  1291. return this._artMeshUserDataNode;
  1292. }
  1293. parseUserData(data, size) {
  1294. let json = new CubismModelUserDataJson(data, size);
  1295. const typeOfArtMesh = ArtMesh;
  1296. const nodeCount = json.getUserDataCount();
  1297. for (let i = 0; i < nodeCount; i++) {
  1298. const addNode = {
  1299. targetId: json.getUserDataId(i),
  1300. targetType: json.getUserDataTargetType(i),
  1301. value: json.getUserDataValue(i)
  1302. };
  1303. this._userDataNodes.push(addNode);
  1304. if (addNode.targetType == typeOfArtMesh) {
  1305. this._artMeshUserDataNode.push(addNode);
  1306. }
  1307. }
  1308. json.release();
  1309. }
  1310. constructor() {
  1311. this._userDataNodes = [];
  1312. this._artMeshUserDataNode = [];
  1313. }
  1314. release() {
  1315. this._userDataNodes = null;
  1316. }
  1317. };
  1318. var ACubismMotion = class {
  1319. constructor() {
  1320. this._fadeInSeconds = -1;
  1321. this._fadeOutSeconds = -1;
  1322. this._weight = 1;
  1323. this._offsetSeconds = 0;
  1324. this._firedEventValues = [];
  1325. }
  1326. release() {
  1327. this._weight = 0;
  1328. }
  1329. updateParameters(model, motionQueueEntry, userTimeSeconds) {
  1330. if (!motionQueueEntry.isAvailable() || motionQueueEntry.isFinished()) {
  1331. return;
  1332. }
  1333. if (!motionQueueEntry.isStarted()) {
  1334. motionQueueEntry.setIsStarted(true);
  1335. motionQueueEntry.setStartTime(userTimeSeconds - this._offsetSeconds);
  1336. motionQueueEntry.setFadeInStartTime(userTimeSeconds);
  1337. const duration = this.getDuration();
  1338. if (motionQueueEntry.getEndTime() < 0) {
  1339. motionQueueEntry.setEndTime(duration <= 0 ? -1 : motionQueueEntry.getStartTime() + duration);
  1340. }
  1341. }
  1342. let fadeWeight = this._weight;
  1343. const fadeIn = this._fadeInSeconds == 0 ? 1 : CubismMath.getEasingSine((userTimeSeconds - motionQueueEntry.getFadeInStartTime()) / this._fadeInSeconds);
  1344. const fadeOut = this._fadeOutSeconds == 0 || motionQueueEntry.getEndTime() < 0 ? 1 : CubismMath.getEasingSine((motionQueueEntry.getEndTime() - userTimeSeconds) / this._fadeOutSeconds);
  1345. fadeWeight = fadeWeight * fadeIn * fadeOut;
  1346. motionQueueEntry.setState(userTimeSeconds, fadeWeight);
  1347. this.doUpdateParameters(model, userTimeSeconds, fadeWeight, motionQueueEntry);
  1348. if (motionQueueEntry.getEndTime() > 0 && motionQueueEntry.getEndTime() < userTimeSeconds) {
  1349. motionQueueEntry.setIsFinished(true);
  1350. }
  1351. }
  1352. setFadeInTime(fadeInSeconds) {
  1353. this._fadeInSeconds = fadeInSeconds;
  1354. }
  1355. setFadeOutTime(fadeOutSeconds) {
  1356. this._fadeOutSeconds = fadeOutSeconds;
  1357. }
  1358. getFadeOutTime() {
  1359. return this._fadeOutSeconds;
  1360. }
  1361. getFadeInTime() {
  1362. return this._fadeInSeconds;
  1363. }
  1364. setWeight(weight) {
  1365. this._weight = weight;
  1366. }
  1367. getWeight() {
  1368. return this._weight;
  1369. }
  1370. getDuration() {
  1371. return -1;
  1372. }
  1373. getLoopDuration() {
  1374. return -1;
  1375. }
  1376. setOffsetTime(offsetSeconds) {
  1377. this._offsetSeconds = offsetSeconds;
  1378. }
  1379. getFiredEvent(beforeCheckTimeSeconds, motionTimeSeconds) {
  1380. return this._firedEventValues;
  1381. }
  1382. setFinishedMotionHandler(onFinishedMotionHandler) {
  1383. this._onFinishedMotion = onFinishedMotionHandler;
  1384. }
  1385. getFinishedMotionHandler() {
  1386. return this._onFinishedMotion;
  1387. }
  1388. };
  1389. var DefaultFadeTime = 1;
  1390. var CubismExpressionMotion = class _CubismExpressionMotion extends ACubismMotion {
  1391. constructor() {
  1392. super();
  1393. this._parameters = [];
  1394. }
  1395. static create(json) {
  1396. const expression = new _CubismExpressionMotion();
  1397. const fadeInTime = json.FadeInTime;
  1398. const fadeOutTime = json.FadeOutTime;
  1399. expression.setFadeInTime(fadeInTime !== void 0 ? fadeInTime : DefaultFadeTime);
  1400. expression.setFadeOutTime(fadeOutTime !== void 0 ? fadeOutTime : DefaultFadeTime);
  1401. const parameters = json.Parameters || [];
  1402. for (let i = 0; i < parameters.length; ++i) {
  1403. const param = parameters[i];
  1404. const parameterId = param.Id;
  1405. const value = param.Value;
  1406. let blendType;
  1407. switch (param.Blend) {
  1408. case "Multiply":
  1409. blendType = ExpressionBlendType.ExpressionBlendType_Multiply;
  1410. break;
  1411. case "Overwrite":
  1412. blendType = ExpressionBlendType.ExpressionBlendType_Overwrite;
  1413. break;
  1414. case "Add":
  1415. default:
  1416. blendType = ExpressionBlendType.ExpressionBlendType_Add;
  1417. break;
  1418. }
  1419. const item = {
  1420. parameterId,
  1421. blendType,
  1422. value
  1423. };
  1424. expression._parameters.push(item);
  1425. }
  1426. return expression;
  1427. }
  1428. doUpdateParameters(model, userTimeSeconds, weight, motionQueueEntry) {
  1429. for (let i = 0; i < this._parameters.length; ++i) {
  1430. const parameter = this._parameters[i];
  1431. switch (parameter.blendType) {
  1432. case ExpressionBlendType.ExpressionBlendType_Add: {
  1433. model.addParameterValueById(parameter.parameterId, parameter.value, weight);
  1434. break;
  1435. }
  1436. case ExpressionBlendType.ExpressionBlendType_Multiply: {
  1437. model.multiplyParameterValueById(parameter.parameterId, parameter.value, weight);
  1438. break;
  1439. }
  1440. case ExpressionBlendType.ExpressionBlendType_Overwrite: {
  1441. model.setParameterValueById(parameter.parameterId, parameter.value, weight);
  1442. break;
  1443. }
  1444. }
  1445. }
  1446. }
  1447. };
  1448. var ExpressionBlendType = ((ExpressionBlendType2) => {
  1449. ExpressionBlendType2[ExpressionBlendType2["ExpressionBlendType_Add"] = 0] = "ExpressionBlendType_Add";
  1450. ExpressionBlendType2[ExpressionBlendType2["ExpressionBlendType_Multiply"] = 1] = "ExpressionBlendType_Multiply";
  1451. ExpressionBlendType2[ExpressionBlendType2["ExpressionBlendType_Overwrite"] = 2] = "ExpressionBlendType_Overwrite";
  1452. return ExpressionBlendType2;
  1453. })(ExpressionBlendType || {});
  1454. var CubismConfig;
  1455. ((CubismConfig2) => {
  1456. CubismConfig2.supportMoreMaskDivisions = true;
  1457. CubismConfig2.setOpacityFromMotion = false;
  1458. })(CubismConfig || (CubismConfig = {}));
  1459. var CubismMotionCurveTarget = ((CubismMotionCurveTarget2) => {
  1460. CubismMotionCurveTarget2[CubismMotionCurveTarget2["CubismMotionCurveTarget_Model"] = 0] = "CubismMotionCurveTarget_Model";
  1461. CubismMotionCurveTarget2[CubismMotionCurveTarget2["CubismMotionCurveTarget_Parameter"] = 1] = "CubismMotionCurveTarget_Parameter";
  1462. CubismMotionCurveTarget2[CubismMotionCurveTarget2["CubismMotionCurveTarget_PartOpacity"] = 2] = "CubismMotionCurveTarget_PartOpacity";
  1463. return CubismMotionCurveTarget2;
  1464. })(CubismMotionCurveTarget || {});
  1465. var CubismMotionSegmentType = ((CubismMotionSegmentType2) => {
  1466. CubismMotionSegmentType2[CubismMotionSegmentType2["CubismMotionSegmentType_Linear"] = 0] = "CubismMotionSegmentType_Linear";
  1467. CubismMotionSegmentType2[CubismMotionSegmentType2["CubismMotionSegmentType_Bezier"] = 1] = "CubismMotionSegmentType_Bezier";
  1468. CubismMotionSegmentType2[CubismMotionSegmentType2["CubismMotionSegmentType_Stepped"] = 2] = "CubismMotionSegmentType_Stepped";
  1469. CubismMotionSegmentType2[CubismMotionSegmentType2["CubismMotionSegmentType_InverseStepped"] = 3] = "CubismMotionSegmentType_InverseStepped";
  1470. return CubismMotionSegmentType2;
  1471. })(CubismMotionSegmentType || {});
  1472. var CubismMotionPoint = class {
  1473. constructor(time = 0, value = 0) {
  1474. this.time = time;
  1475. this.value = value;
  1476. }
  1477. };
  1478. var CubismMotionSegment = class {
  1479. constructor() {
  1480. this.basePointIndex = 0;
  1481. this.segmentType = 0;
  1482. }
  1483. };
  1484. var CubismMotionCurve = class {
  1485. constructor() {
  1486. this.id = "";
  1487. this.type = 0;
  1488. this.segmentCount = 0;
  1489. this.baseSegmentIndex = 0;
  1490. this.fadeInTime = 0;
  1491. this.fadeOutTime = 0;
  1492. }
  1493. };
  1494. var CubismMotionEvent = class {
  1495. constructor() {
  1496. this.fireTime = 0;
  1497. this.value = "";
  1498. }
  1499. };
  1500. var CubismMotionData = class {
  1501. constructor() {
  1502. this.duration = 0;
  1503. this.loop = false;
  1504. this.curveCount = 0;
  1505. this.eventCount = 0;
  1506. this.fps = 0;
  1507. this.curves = [];
  1508. this.segments = [];
  1509. this.points = [];
  1510. this.events = [];
  1511. }
  1512. };
  1513. var CubismMotionJson = class {
  1514. constructor(json) {
  1515. this._json = json;
  1516. }
  1517. release() {
  1518. this._json = void 0;
  1519. }
  1520. getMotionDuration() {
  1521. return this._json.Meta.Duration;
  1522. }
  1523. isMotionLoop() {
  1524. return this._json.Meta.Loop || false;
  1525. }
  1526. getEvaluationOptionFlag(flagType) {
  1527. if (EvaluationOptionFlag.EvaluationOptionFlag_AreBeziersRistricted == flagType) {
  1528. return !!this._json.Meta.AreBeziersRestricted;
  1529. }
  1530. return false;
  1531. }
  1532. getMotionCurveCount() {
  1533. return this._json.Meta.CurveCount;
  1534. }
  1535. getMotionFps() {
  1536. return this._json.Meta.Fps;
  1537. }
  1538. getMotionTotalSegmentCount() {
  1539. return this._json.Meta.TotalSegmentCount;
  1540. }
  1541. getMotionTotalPointCount() {
  1542. return this._json.Meta.TotalPointCount;
  1543. }
  1544. getMotionFadeInTime() {
  1545. return this._json.Meta.FadeInTime;
  1546. }
  1547. getMotionFadeOutTime() {
  1548. return this._json.Meta.FadeOutTime;
  1549. }
  1550. getMotionCurveTarget(curveIndex) {
  1551. return this._json.Curves[curveIndex].Target;
  1552. }
  1553. getMotionCurveId(curveIndex) {
  1554. return this._json.Curves[curveIndex].Id;
  1555. }
  1556. getMotionCurveFadeInTime(curveIndex) {
  1557. return this._json.Curves[curveIndex].FadeInTime;
  1558. }
  1559. getMotionCurveFadeOutTime(curveIndex) {
  1560. return this._json.Curves[curveIndex].FadeOutTime;
  1561. }
  1562. getMotionCurveSegmentCount(curveIndex) {
  1563. return this._json.Curves[curveIndex].Segments.length;
  1564. }
  1565. getMotionCurveSegment(curveIndex, segmentIndex) {
  1566. return this._json.Curves[curveIndex].Segments[segmentIndex];
  1567. }
  1568. getEventCount() {
  1569. return this._json.Meta.UserDataCount || 0;
  1570. }
  1571. getTotalEventValueSize() {
  1572. return this._json.Meta.TotalUserDataSize;
  1573. }
  1574. getEventTime(userDataIndex) {
  1575. return this._json.UserData[userDataIndex].Time;
  1576. }
  1577. getEventValue(userDataIndex) {
  1578. return this._json.UserData[userDataIndex].Value;
  1579. }
  1580. };
  1581. var EvaluationOptionFlag = ((EvaluationOptionFlag2) => {
  1582. EvaluationOptionFlag2[EvaluationOptionFlag2["EvaluationOptionFlag_AreBeziersRistricted"] = 0] = "EvaluationOptionFlag_AreBeziersRistricted";
  1583. return EvaluationOptionFlag2;
  1584. })(EvaluationOptionFlag || {});
  1585. var EffectNameEyeBlink = "EyeBlink";
  1586. var EffectNameLipSync = "LipSync";
  1587. var TargetNameModel = "Model";
  1588. var TargetNameParameter = "Parameter";
  1589. var TargetNamePartOpacity = "PartOpacity";
  1590. var UseOldBeziersCurveMotion = false;
  1591. function lerpPoints(a, b, t) {
  1592. const result = new CubismMotionPoint();
  1593. result.time = a.time + (b.time - a.time) * t;
  1594. result.value = a.value + (b.value - a.value) * t;
  1595. return result;
  1596. }
  1597. function linearEvaluate(points, time) {
  1598. let t = (time - points[0].time) / (points[1].time - points[0].time);
  1599. if (t < 0) {
  1600. t = 0;
  1601. }
  1602. return points[0].value + (points[1].value - points[0].value) * t;
  1603. }
  1604. function bezierEvaluate(points, time) {
  1605. let t = (time - points[0].time) / (points[3].time - points[0].time);
  1606. if (t < 0) {
  1607. t = 0;
  1608. }
  1609. const p01 = lerpPoints(points[0], points[1], t);
  1610. const p12 = lerpPoints(points[1], points[2], t);
  1611. const p23 = lerpPoints(points[2], points[3], t);
  1612. const p012 = lerpPoints(p01, p12, t);
  1613. const p123 = lerpPoints(p12, p23, t);
  1614. return lerpPoints(p012, p123, t).value;
  1615. }
  1616. function bezierEvaluateCardanoInterpretation(points, time) {
  1617. const x = time;
  1618. const x1 = points[0].time;
  1619. const x2 = points[3].time;
  1620. const cx1 = points[1].time;
  1621. const cx2 = points[2].time;
  1622. const a = x2 - 3 * cx2 + 3 * cx1 - x1;
  1623. const b = 3 * cx2 - 6 * cx1 + 3 * x1;
  1624. const c = 3 * cx1 - 3 * x1;
  1625. const d = x1 - x;
  1626. const t = CubismMath.cardanoAlgorithmForBezier(a, b, c, d);
  1627. const p01 = lerpPoints(points[0], points[1], t);
  1628. const p12 = lerpPoints(points[1], points[2], t);
  1629. const p23 = lerpPoints(points[2], points[3], t);
  1630. const p012 = lerpPoints(p01, p12, t);
  1631. const p123 = lerpPoints(p12, p23, t);
  1632. return lerpPoints(p012, p123, t).value;
  1633. }
  1634. function steppedEvaluate(points, time) {
  1635. return points[0].value;
  1636. }
  1637. function inverseSteppedEvaluate(points, time) {
  1638. return points[1].value;
  1639. }
  1640. function evaluateCurve(motionData, index, time) {
  1641. const curve = motionData.curves[index];
  1642. let target = -1;
  1643. const totalSegmentCount = curve.baseSegmentIndex + curve.segmentCount;
  1644. let pointPosition = 0;
  1645. for (let i = curve.baseSegmentIndex; i < totalSegmentCount; ++i) {
  1646. pointPosition = motionData.segments[i].basePointIndex + (motionData.segments[i].segmentType == CubismMotionSegmentType.CubismMotionSegmentType_Bezier ? 3 : 1);
  1647. if (motionData.points[pointPosition].time > time) {
  1648. target = i;
  1649. break;
  1650. }
  1651. }
  1652. if (target == -1) {
  1653. return motionData.points[pointPosition].value;
  1654. }
  1655. const segment = motionData.segments[target];
  1656. return segment.evaluate(motionData.points.slice(segment.basePointIndex), time);
  1657. }
  1658. var CubismMotion = class _CubismMotion extends ACubismMotion {
  1659. constructor() {
  1660. super();
  1661. this._eyeBlinkParameterIds = [];
  1662. this._lipSyncParameterIds = [];
  1663. this._sourceFrameRate = 30;
  1664. this._loopDurationSeconds = -1;
  1665. this._isLoop = false;
  1666. this._isLoopFadeIn = true;
  1667. this._lastWeight = 0;
  1668. }
  1669. static create(json, onFinishedMotionHandler) {
  1670. const ret = new _CubismMotion();
  1671. ret.parse(json);
  1672. ret._sourceFrameRate = ret._motionData.fps;
  1673. ret._loopDurationSeconds = ret._motionData.duration;
  1674. ret._onFinishedMotion = onFinishedMotionHandler;
  1675. return ret;
  1676. }
  1677. doUpdateParameters(model, userTimeSeconds, fadeWeight, motionQueueEntry) {
  1678. if (this._modelCurveIdEyeBlink == null) {
  1679. this._modelCurveIdEyeBlink = EffectNameEyeBlink;
  1680. }
  1681. if (this._modelCurveIdLipSync == null) {
  1682. this._modelCurveIdLipSync = EffectNameLipSync;
  1683. }
  1684. let timeOffsetSeconds = userTimeSeconds - motionQueueEntry.getStartTime();
  1685. if (timeOffsetSeconds < 0) {
  1686. timeOffsetSeconds = 0;
  1687. }
  1688. let lipSyncValue = Number.MAX_VALUE;
  1689. let eyeBlinkValue = Number.MAX_VALUE;
  1690. const MaxTargetSize = 64;
  1691. let lipSyncFlags = 0;
  1692. let eyeBlinkFlags = 0;
  1693. if (this._eyeBlinkParameterIds.length > MaxTargetSize) {
  1694. CubismLogDebug("too many eye blink targets : {0}", this._eyeBlinkParameterIds.length);
  1695. }
  1696. if (this._lipSyncParameterIds.length > MaxTargetSize) {
  1697. CubismLogDebug("too many lip sync targets : {0}", this._lipSyncParameterIds.length);
  1698. }
  1699. const tmpFadeIn = this._fadeInSeconds <= 0 ? 1 : CubismMath.getEasingSine((userTimeSeconds - motionQueueEntry.getFadeInStartTime()) / this._fadeInSeconds);
  1700. const tmpFadeOut = this._fadeOutSeconds <= 0 || motionQueueEntry.getEndTime() < 0 ? 1 : CubismMath.getEasingSine((motionQueueEntry.getEndTime() - userTimeSeconds) / this._fadeOutSeconds);
  1701. let value;
  1702. let c, parameterIndex;
  1703. let time = timeOffsetSeconds;
  1704. if (this._isLoop) {
  1705. while (time > this._motionData.duration) {
  1706. time -= this._motionData.duration;
  1707. }
  1708. }
  1709. const curves = this._motionData.curves;
  1710. for (c = 0; c < this._motionData.curveCount && curves[c].type == CubismMotionCurveTarget.CubismMotionCurveTarget_Model; ++c) {
  1711. value = evaluateCurve(this._motionData, c, time);
  1712. if (curves[c].id == this._modelCurveIdEyeBlink) {
  1713. eyeBlinkValue = value;
  1714. } else if (curves[c].id == this._modelCurveIdLipSync) {
  1715. lipSyncValue = value;
  1716. }
  1717. }
  1718. for (; c < this._motionData.curveCount && curves[c].type == CubismMotionCurveTarget.CubismMotionCurveTarget_Parameter; ++c) {
  1719. parameterIndex = model.getParameterIndex(curves[c].id);
  1720. if (parameterIndex == -1) {
  1721. continue;
  1722. }
  1723. const sourceValue = model.getParameterValueByIndex(parameterIndex);
  1724. value = evaluateCurve(this._motionData, c, time);
  1725. if (eyeBlinkValue != Number.MAX_VALUE) {
  1726. for (let i = 0; i < this._eyeBlinkParameterIds.length && i < MaxTargetSize; ++i) {
  1727. if (this._eyeBlinkParameterIds[i] == curves[c].id) {
  1728. value *= eyeBlinkValue;
  1729. eyeBlinkFlags |= 1 << i;
  1730. break;
  1731. }
  1732. }
  1733. }
  1734. if (lipSyncValue != Number.MAX_VALUE) {
  1735. for (let i = 0; i < this._lipSyncParameterIds.length && i < MaxTargetSize; ++i) {
  1736. if (this._lipSyncParameterIds[i] == curves[c].id) {
  1737. value += lipSyncValue;
  1738. lipSyncFlags |= 1 << i;
  1739. break;
  1740. }
  1741. }
  1742. }
  1743. let v;
  1744. if (curves[c].fadeInTime < 0 && curves[c].fadeOutTime < 0) {
  1745. v = sourceValue + (value - sourceValue) * fadeWeight;
  1746. } else {
  1747. let fin;
  1748. let fout;
  1749. if (curves[c].fadeInTime < 0) {
  1750. fin = tmpFadeIn;
  1751. } else {
  1752. fin = curves[c].fadeInTime == 0 ? 1 : CubismMath.getEasingSine((userTimeSeconds - motionQueueEntry.getFadeInStartTime()) / curves[c].fadeInTime);
  1753. }
  1754. if (curves[c].fadeOutTime < 0) {
  1755. fout = tmpFadeOut;
  1756. } else {
  1757. fout = curves[c].fadeOutTime == 0 || motionQueueEntry.getEndTime() < 0 ? 1 : CubismMath.getEasingSine((motionQueueEntry.getEndTime() - userTimeSeconds) / curves[c].fadeOutTime);
  1758. }
  1759. const paramWeight = this._weight * fin * fout;
  1760. v = sourceValue + (value - sourceValue) * paramWeight;
  1761. }
  1762. model.setParameterValueByIndex(parameterIndex, v, 1);
  1763. }
  1764. {
  1765. if (eyeBlinkValue != Number.MAX_VALUE) {
  1766. for (let i = 0; i < this._eyeBlinkParameterIds.length && i < MaxTargetSize; ++i) {
  1767. const sourceValue = model.getParameterValueById(this._eyeBlinkParameterIds[i]);
  1768. if (eyeBlinkFlags >> i & 1) {
  1769. continue;
  1770. }
  1771. const v = sourceValue + (eyeBlinkValue - sourceValue) * fadeWeight;
  1772. model.setParameterValueById(this._eyeBlinkParameterIds[i], v);
  1773. }
  1774. }
  1775. if (lipSyncValue != Number.MAX_VALUE) {
  1776. for (let i = 0; i < this._lipSyncParameterIds.length && i < MaxTargetSize; ++i) {
  1777. const sourceValue = model.getParameterValueById(this._lipSyncParameterIds[i]);
  1778. if (lipSyncFlags >> i & 1) {
  1779. continue;
  1780. }
  1781. const v = sourceValue + (lipSyncValue - sourceValue) * fadeWeight;
  1782. model.setParameterValueById(this._lipSyncParameterIds[i], v);
  1783. }
  1784. }
  1785. }
  1786. for (; c < this._motionData.curveCount && curves[c].type == CubismMotionCurveTarget.CubismMotionCurveTarget_PartOpacity; ++c) {
  1787. value = evaluateCurve(this._motionData, c, time);
  1788. if (CubismConfig.setOpacityFromMotion) {
  1789. model.setPartOpacityById(curves[c].id, value);
  1790. } else {
  1791. parameterIndex = model.getParameterIndex(curves[c].id);
  1792. if (parameterIndex == -1) {
  1793. continue;
  1794. }
  1795. model.setParameterValueByIndex(parameterIndex, value);
  1796. }
  1797. }
  1798. if (timeOffsetSeconds >= this._motionData.duration) {
  1799. if (this._isLoop) {
  1800. motionQueueEntry.setStartTime(userTimeSeconds);
  1801. if (this._isLoopFadeIn) {
  1802. motionQueueEntry.setFadeInStartTime(userTimeSeconds);
  1803. }
  1804. } else {
  1805. if (this._onFinishedMotion) {
  1806. this._onFinishedMotion(this);
  1807. }
  1808. motionQueueEntry.setIsFinished(true);
  1809. }
  1810. }
  1811. this._lastWeight = fadeWeight;
  1812. }
  1813. setIsLoop(loop) {
  1814. this._isLoop = loop;
  1815. }
  1816. isLoop() {
  1817. return this._isLoop;
  1818. }
  1819. setIsLoopFadeIn(loopFadeIn) {
  1820. this._isLoopFadeIn = loopFadeIn;
  1821. }
  1822. isLoopFadeIn() {
  1823. return this._isLoopFadeIn;
  1824. }
  1825. getDuration() {
  1826. return this._isLoop ? -1 : this._loopDurationSeconds;
  1827. }
  1828. getLoopDuration() {
  1829. return this._loopDurationSeconds;
  1830. }
  1831. setParameterFadeInTime(parameterId, value) {
  1832. const curves = this._motionData.curves;
  1833. for (let i = 0; i < this._motionData.curveCount; ++i) {
  1834. if (parameterId == curves[i].id) {
  1835. curves[i].fadeInTime = value;
  1836. return;
  1837. }
  1838. }
  1839. }
  1840. setParameterFadeOutTime(parameterId, value) {
  1841. const curves = this._motionData.curves;
  1842. for (let i = 0; i < this._motionData.curveCount; ++i) {
  1843. if (parameterId == curves[i].id) {
  1844. curves[i].fadeOutTime = value;
  1845. return;
  1846. }
  1847. }
  1848. }
  1849. getParameterFadeInTime(parameterId) {
  1850. const curves = this._motionData.curves;
  1851. for (let i = 0; i < this._motionData.curveCount; ++i) {
  1852. if (parameterId == curves[i].id) {
  1853. return curves[i].fadeInTime;
  1854. }
  1855. }
  1856. return -1;
  1857. }
  1858. getParameterFadeOutTime(parameterId) {
  1859. const curves = this._motionData.curves;
  1860. for (let i = 0; i < this._motionData.curveCount; ++i) {
  1861. if (parameterId == curves[i].id) {
  1862. return curves[i].fadeOutTime;
  1863. }
  1864. }
  1865. return -1;
  1866. }
  1867. setEffectIds(eyeBlinkParameterIds, lipSyncParameterIds) {
  1868. this._eyeBlinkParameterIds = eyeBlinkParameterIds;
  1869. this._lipSyncParameterIds = lipSyncParameterIds;
  1870. }
  1871. release() {
  1872. this._motionData = void 0;
  1873. }
  1874. parse(motionJson) {
  1875. this._motionData = new CubismMotionData();
  1876. let json = new CubismMotionJson(motionJson);
  1877. this._motionData.duration = json.getMotionDuration();
  1878. this._motionData.loop = json.isMotionLoop();
  1879. this._motionData.curveCount = json.getMotionCurveCount();
  1880. this._motionData.fps = json.getMotionFps();
  1881. this._motionData.eventCount = json.getEventCount();
  1882. const areBeziersRestructed = json.getEvaluationOptionFlag(EvaluationOptionFlag.EvaluationOptionFlag_AreBeziersRistricted);
  1883. const fadeInSeconds = json.getMotionFadeInTime();
  1884. const fadeOutSeconds = json.getMotionFadeOutTime();
  1885. if (fadeInSeconds !== void 0) {
  1886. this._fadeInSeconds = fadeInSeconds < 0 ? 1 : fadeInSeconds;
  1887. } else {
  1888. this._fadeInSeconds = 1;
  1889. }
  1890. if (fadeOutSeconds !== void 0) {
  1891. this._fadeOutSeconds = fadeOutSeconds < 0 ? 1 : fadeOutSeconds;
  1892. } else {
  1893. this._fadeOutSeconds = 1;
  1894. }
  1895. this._motionData.curves = Array.from({ length: this._motionData.curveCount }).map(() => new CubismMotionCurve());
  1896. this._motionData.segments = Array.from({ length: json.getMotionTotalSegmentCount() }).map(() => new CubismMotionSegment());
  1897. this._motionData.events = Array.from({ length: this._motionData.eventCount }).map(() => new CubismMotionEvent());
  1898. this._motionData.points = [];
  1899. let totalPointCount = 0;
  1900. let totalSegmentCount = 0;
  1901. for (let curveCount = 0; curveCount < this._motionData.curveCount; ++curveCount) {
  1902. const curve = this._motionData.curves[curveCount];
  1903. switch (json.getMotionCurveTarget(curveCount)) {
  1904. case TargetNameModel:
  1905. curve.type = CubismMotionCurveTarget.CubismMotionCurveTarget_Model;
  1906. break;
  1907. case TargetNameParameter:
  1908. curve.type = CubismMotionCurveTarget.CubismMotionCurveTarget_Parameter;
  1909. break;
  1910. case TargetNamePartOpacity:
  1911. curve.type = CubismMotionCurveTarget.CubismMotionCurveTarget_PartOpacity;
  1912. break;
  1913. default:
  1914. CubismLogWarning('Warning : Unable to get segment type from Curve! The number of "CurveCount" may be incorrect!');
  1915. }
  1916. curve.id = json.getMotionCurveId(curveCount);
  1917. curve.baseSegmentIndex = totalSegmentCount;
  1918. const fadeInTime = json.getMotionCurveFadeInTime(curveCount);
  1919. const fadeOutTime = json.getMotionCurveFadeOutTime(curveCount);
  1920. curve.fadeInTime = fadeInTime !== void 0 ? fadeInTime : -1;
  1921. curve.fadeOutTime = fadeOutTime !== void 0 ? fadeOutTime : -1;
  1922. for (let segmentPosition = 0; segmentPosition < json.getMotionCurveSegmentCount(curveCount); ) {
  1923. if (segmentPosition == 0) {
  1924. this._motionData.segments[totalSegmentCount].basePointIndex = totalPointCount;
  1925. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition), json.getMotionCurveSegment(curveCount, segmentPosition + 1));
  1926. totalPointCount += 1;
  1927. segmentPosition += 2;
  1928. } else {
  1929. this._motionData.segments[totalSegmentCount].basePointIndex = totalPointCount - 1;
  1930. }
  1931. const segment = json.getMotionCurveSegment(curveCount, segmentPosition);
  1932. switch (segment) {
  1933. case CubismMotionSegmentType.CubismMotionSegmentType_Linear: {
  1934. this._motionData.segments[totalSegmentCount].segmentType = CubismMotionSegmentType.CubismMotionSegmentType_Linear;
  1935. this._motionData.segments[totalSegmentCount].evaluate = linearEvaluate;
  1936. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 1), json.getMotionCurveSegment(curveCount, segmentPosition + 2));
  1937. totalPointCount += 1;
  1938. segmentPosition += 3;
  1939. break;
  1940. }
  1941. case CubismMotionSegmentType.CubismMotionSegmentType_Bezier: {
  1942. this._motionData.segments[totalSegmentCount].segmentType = CubismMotionSegmentType.CubismMotionSegmentType_Bezier;
  1943. if (areBeziersRestructed || UseOldBeziersCurveMotion) {
  1944. this._motionData.segments[totalSegmentCount].evaluate = bezierEvaluate;
  1945. } else {
  1946. this._motionData.segments[totalSegmentCount].evaluate = bezierEvaluateCardanoInterpretation;
  1947. }
  1948. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 1), json.getMotionCurveSegment(curveCount, segmentPosition + 2));
  1949. this._motionData.points[totalPointCount + 1] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 3), json.getMotionCurveSegment(curveCount, segmentPosition + 4));
  1950. this._motionData.points[totalPointCount + 2] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 5), json.getMotionCurveSegment(curveCount, segmentPosition + 6));
  1951. totalPointCount += 3;
  1952. segmentPosition += 7;
  1953. break;
  1954. }
  1955. case CubismMotionSegmentType.CubismMotionSegmentType_Stepped: {
  1956. this._motionData.segments[totalSegmentCount].segmentType = CubismMotionSegmentType.CubismMotionSegmentType_Stepped;
  1957. this._motionData.segments[totalSegmentCount].evaluate = steppedEvaluate;
  1958. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 1), json.getMotionCurveSegment(curveCount, segmentPosition + 2));
  1959. totalPointCount += 1;
  1960. segmentPosition += 3;
  1961. break;
  1962. }
  1963. case CubismMotionSegmentType.CubismMotionSegmentType_InverseStepped: {
  1964. this._motionData.segments[totalSegmentCount].segmentType = CubismMotionSegmentType.CubismMotionSegmentType_InverseStepped;
  1965. this._motionData.segments[totalSegmentCount].evaluate = inverseSteppedEvaluate;
  1966. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 1), json.getMotionCurveSegment(curveCount, segmentPosition + 2));
  1967. totalPointCount += 1;
  1968. segmentPosition += 3;
  1969. break;
  1970. }
  1971. }
  1972. ++curve.segmentCount;
  1973. ++totalSegmentCount;
  1974. }
  1975. this._motionData.curves.push(curve);
  1976. }
  1977. for (let userdatacount = 0; userdatacount < json.getEventCount(); ++userdatacount) {
  1978. this._motionData.events[userdatacount].fireTime = json.getEventTime(userdatacount);
  1979. this._motionData.events[userdatacount].value = json.getEventValue(userdatacount);
  1980. }
  1981. json.release();
  1982. }
  1983. getFiredEvent(beforeCheckTimeSeconds, motionTimeSeconds) {
  1984. this._firedEventValues.length = 0;
  1985. for (let u = 0; u < this._motionData.eventCount; ++u) {
  1986. if (this._motionData.events[u].fireTime > beforeCheckTimeSeconds && this._motionData.events[u].fireTime <= motionTimeSeconds) {
  1987. this._firedEventValues.push(this._motionData.events[u].value);
  1988. }
  1989. }
  1990. return this._firedEventValues;
  1991. }
  1992. };
  1993. var CubismMotionQueueEntry = class {
  1994. constructor() {
  1995. this._autoDelete = false;
  1996. this._available = true;
  1997. this._finished = false;
  1998. this._started = false;
  1999. this._startTimeSeconds = -1;
  2000. this._fadeInStartTimeSeconds = 0;
  2001. this._endTimeSeconds = -1;
  2002. this._stateTimeSeconds = 0;
  2003. this._stateWeight = 0;
  2004. this._lastEventCheckSeconds = 0;
  2005. this._motionQueueEntryHandle = this;
  2006. this._fadeOutSeconds = 0;
  2007. this._isTriggeredFadeOut = false;
  2008. }
  2009. release() {
  2010. if (this._autoDelete && this._motion) {
  2011. this._motion.release();
  2012. }
  2013. }
  2014. setFadeOut(fadeOutSeconds) {
  2015. this._fadeOutSeconds = fadeOutSeconds;
  2016. this._isTriggeredFadeOut = true;
  2017. }
  2018. startFadeOut(fadeOutSeconds, userTimeSeconds) {
  2019. const newEndTimeSeconds = userTimeSeconds + fadeOutSeconds;
  2020. this._isTriggeredFadeOut = true;
  2021. if (this._endTimeSeconds < 0 || newEndTimeSeconds < this._endTimeSeconds) {
  2022. this._endTimeSeconds = newEndTimeSeconds;
  2023. }
  2024. }
  2025. isFinished() {
  2026. return this._finished;
  2027. }
  2028. isStarted() {
  2029. return this._started;
  2030. }
  2031. getStartTime() {
  2032. return this._startTimeSeconds;
  2033. }
  2034. getFadeInStartTime() {
  2035. return this._fadeInStartTimeSeconds;
  2036. }
  2037. getEndTime() {
  2038. return this._endTimeSeconds;
  2039. }
  2040. setStartTime(startTime) {
  2041. this._startTimeSeconds = startTime;
  2042. }
  2043. setFadeInStartTime(startTime) {
  2044. this._fadeInStartTimeSeconds = startTime;
  2045. }
  2046. setEndTime(endTime) {
  2047. this._endTimeSeconds = endTime;
  2048. }
  2049. setIsFinished(f) {
  2050. this._finished = f;
  2051. }
  2052. setIsStarted(f) {
  2053. this._started = f;
  2054. }
  2055. isAvailable() {
  2056. return this._available;
  2057. }
  2058. setIsAvailable(v) {
  2059. this._available = v;
  2060. }
  2061. setState(timeSeconds, weight) {
  2062. this._stateTimeSeconds = timeSeconds;
  2063. this._stateWeight = weight;
  2064. }
  2065. getStateTime() {
  2066. return this._stateTimeSeconds;
  2067. }
  2068. getStateWeight() {
  2069. return this._stateWeight;
  2070. }
  2071. getLastCheckEventSeconds() {
  2072. return this._lastEventCheckSeconds;
  2073. }
  2074. setLastCheckEventSeconds(checkSeconds) {
  2075. this._lastEventCheckSeconds = checkSeconds;
  2076. }
  2077. isTriggeredFadeOut() {
  2078. return this._isTriggeredFadeOut;
  2079. }
  2080. getFadeOutSeconds() {
  2081. return this._fadeOutSeconds;
  2082. }
  2083. };
  2084. var CubismMotionQueueManager = class {
  2085. constructor() {
  2086. this._userTimeSeconds = 0;
  2087. this._eventCustomData = null;
  2088. this._motions = [];
  2089. }
  2090. release() {
  2091. for (let i = 0; i < this._motions.length; ++i) {
  2092. if (this._motions[i]) {
  2093. this._motions[i].release();
  2094. }
  2095. }
  2096. this._motions = void 0;
  2097. }
  2098. startMotion(motion, autoDelete, userTimeSeconds) {
  2099. if (motion == null) {
  2100. return InvalidMotionQueueEntryHandleValue;
  2101. }
  2102. let motionQueueEntry;
  2103. for (let i = 0; i < this._motions.length; ++i) {
  2104. motionQueueEntry = this._motions[i];
  2105. if (motionQueueEntry == null) {
  2106. continue;
  2107. }
  2108. motionQueueEntry.setFadeOut(motionQueueEntry._motion.getFadeOutTime());
  2109. }
  2110. motionQueueEntry = new CubismMotionQueueEntry();
  2111. motionQueueEntry._autoDelete = autoDelete;
  2112. motionQueueEntry._motion = motion;
  2113. this._motions.push(motionQueueEntry);
  2114. return motionQueueEntry._motionQueueEntryHandle;
  2115. }
  2116. isFinished() {
  2117. let i = 0;
  2118. while (i < this._motions.length) {
  2119. const motionQueueEntry = this._motions[i];
  2120. if (motionQueueEntry == null) {
  2121. this._motions.splice(i, 1);
  2122. continue;
  2123. }
  2124. const motion = motionQueueEntry._motion;
  2125. if (motion == null) {
  2126. motionQueueEntry.release();
  2127. this._motions.splice(i, 1);
  2128. continue;
  2129. }
  2130. if (!motionQueueEntry.isFinished()) {
  2131. return false;
  2132. }
  2133. i++;
  2134. }
  2135. return true;
  2136. }
  2137. isFinishedByHandle(motionQueueEntryNumber) {
  2138. for (let i = 0; i < this._motions.length; i++) {
  2139. const motionQueueEntry = this._motions[i];
  2140. if (motionQueueEntry == null) {
  2141. continue;
  2142. }
  2143. if (motionQueueEntry._motionQueueEntryHandle == motionQueueEntryNumber && !motionQueueEntry.isFinished()) {
  2144. return false;
  2145. }
  2146. }
  2147. return true;
  2148. }
  2149. stopAllMotions() {
  2150. for (let i = 0; i < this._motions.length; i++) {
  2151. const motionQueueEntry = this._motions[i];
  2152. if (motionQueueEntry != null) {
  2153. motionQueueEntry.release();
  2154. }
  2155. }
  2156. this._motions = [];
  2157. }
  2158. getCubismMotionQueueEntry(motionQueueEntryNumber) {
  2159. return this._motions.find((entry) => entry != null && entry._motionQueueEntryHandle == motionQueueEntryNumber);
  2160. }
  2161. setEventCallback(callback, customData = null) {
  2162. this._eventCallBack = callback;
  2163. this._eventCustomData = customData;
  2164. }
  2165. doUpdateMotion(model, userTimeSeconds) {
  2166. let updated = false;
  2167. let i = 0;
  2168. while (i < this._motions.length) {
  2169. const motionQueueEntry = this._motions[i];
  2170. if (motionQueueEntry == null) {
  2171. this._motions.splice(i, 1);
  2172. continue;
  2173. }
  2174. const motion = motionQueueEntry._motion;
  2175. if (motion == null) {
  2176. motionQueueEntry.release();
  2177. this._motions.splice(i, 1);
  2178. continue;
  2179. }
  2180. motion.updateParameters(model, motionQueueEntry, userTimeSeconds);
  2181. updated = true;
  2182. const firedList = motion.getFiredEvent(motionQueueEntry.getLastCheckEventSeconds() - motionQueueEntry.getStartTime(), userTimeSeconds - motionQueueEntry.getStartTime());
  2183. for (let i2 = 0; i2 < firedList.length; ++i2) {
  2184. this._eventCallBack(this, firedList[i2], this._eventCustomData);
  2185. }
  2186. motionQueueEntry.setLastCheckEventSeconds(userTimeSeconds);
  2187. if (motionQueueEntry.isFinished()) {
  2188. motionQueueEntry.release();
  2189. this._motions.splice(i, 1);
  2190. } else {
  2191. if (motionQueueEntry.isTriggeredFadeOut()) {
  2192. motionQueueEntry.startFadeOut(motionQueueEntry.getFadeOutSeconds(), userTimeSeconds);
  2193. }
  2194. i++;
  2195. }
  2196. }
  2197. return updated;
  2198. }
  2199. };
  2200. var InvalidMotionQueueEntryHandleValue = -1;
  2201. var CubismMotionManager = class extends CubismMotionQueueManager {
  2202. constructor() {
  2203. super();
  2204. this._currentPriority = 0;
  2205. this._reservePriority = 0;
  2206. }
  2207. getCurrentPriority() {
  2208. return this._currentPriority;
  2209. }
  2210. getReservePriority() {
  2211. return this._reservePriority;
  2212. }
  2213. setReservePriority(val) {
  2214. this._reservePriority = val;
  2215. }
  2216. startMotionPriority(motion, autoDelete, priority) {
  2217. if (priority == this._reservePriority) {
  2218. this._reservePriority = 0;
  2219. }
  2220. this._currentPriority = priority;
  2221. return super.startMotion(motion, autoDelete, this._userTimeSeconds);
  2222. }
  2223. updateMotion(model, deltaTimeSeconds) {
  2224. this._userTimeSeconds += deltaTimeSeconds;
  2225. const updated = super.doUpdateMotion(model, this._userTimeSeconds);
  2226. if (this.isFinished()) {
  2227. this._currentPriority = 0;
  2228. }
  2229. return updated;
  2230. }
  2231. reserveMotion(priority) {
  2232. if (priority <= this._reservePriority || priority <= this._currentPriority) {
  2233. return false;
  2234. }
  2235. this._reservePriority = priority;
  2236. return true;
  2237. }
  2238. };
  2239. var CubismPhysicsTargetType = ((CubismPhysicsTargetType2) => {
  2240. CubismPhysicsTargetType2[CubismPhysicsTargetType2["CubismPhysicsTargetType_Parameter"] = 0] = "CubismPhysicsTargetType_Parameter";
  2241. return CubismPhysicsTargetType2;
  2242. })(CubismPhysicsTargetType || {});
  2243. var CubismPhysicsSource = ((CubismPhysicsSource2) => {
  2244. CubismPhysicsSource2[CubismPhysicsSource2["CubismPhysicsSource_X"] = 0] = "CubismPhysicsSource_X";
  2245. CubismPhysicsSource2[CubismPhysicsSource2["CubismPhysicsSource_Y"] = 1] = "CubismPhysicsSource_Y";
  2246. CubismPhysicsSource2[CubismPhysicsSource2["CubismPhysicsSource_Angle"] = 2] = "CubismPhysicsSource_Angle";
  2247. return CubismPhysicsSource2;
  2248. })(CubismPhysicsSource || {});
  2249. var PhysicsJsonEffectiveForces = class {
  2250. constructor() {
  2251. this.gravity = new CubismVector2(0, 0);
  2252. this.wind = new CubismVector2(0, 0);
  2253. }
  2254. };
  2255. var CubismPhysicsParticle = class {
  2256. constructor() {
  2257. this.initialPosition = new CubismVector2(0, 0);
  2258. this.position = new CubismVector2(0, 0);
  2259. this.lastPosition = new CubismVector2(0, 0);
  2260. this.lastGravity = new CubismVector2(0, 0);
  2261. this.force = new CubismVector2(0, 0);
  2262. this.velocity = new CubismVector2(0, 0);
  2263. }
  2264. };
  2265. var CubismPhysicsSubRig = class {
  2266. constructor() {
  2267. this.normalizationPosition = {};
  2268. this.normalizationAngle = {};
  2269. }
  2270. };
  2271. var CubismPhysicsInput = class {
  2272. constructor() {
  2273. this.source = {};
  2274. }
  2275. };
  2276. var CubismPhysicsOutput = class {
  2277. constructor() {
  2278. this.destination = {};
  2279. this.translationScale = new CubismVector2(0, 0);
  2280. }
  2281. };
  2282. var CubismPhysicsRig = class {
  2283. constructor() {
  2284. this.settings = [];
  2285. this.inputs = [];
  2286. this.outputs = [];
  2287. this.particles = [];
  2288. this.gravity = new CubismVector2(0, 0);
  2289. this.wind = new CubismVector2(0, 0);
  2290. }
  2291. };
  2292. var CubismPhysicsJson = class {
  2293. constructor(json) {
  2294. this._json = json;
  2295. }
  2296. release() {
  2297. this._json = void 0;
  2298. }
  2299. getGravity() {
  2300. const ret = new CubismVector2(0, 0);
  2301. ret.x = this._json.Meta.EffectiveForces.Gravity.X;
  2302. ret.y = this._json.Meta.EffectiveForces.Gravity.Y;
  2303. return ret;
  2304. }
  2305. getWind() {
  2306. const ret = new CubismVector2(0, 0);
  2307. ret.x = this._json.Meta.EffectiveForces.Wind.X;
  2308. ret.y = this._json.Meta.EffectiveForces.Wind.Y;
  2309. return ret;
  2310. }
  2311. getSubRigCount() {
  2312. return this._json.Meta.PhysicsSettingCount;
  2313. }
  2314. getTotalInputCount() {
  2315. return this._json.Meta.TotalInputCount;
  2316. }
  2317. getTotalOutputCount() {
  2318. return this._json.Meta.TotalOutputCount;
  2319. }
  2320. getVertexCount() {
  2321. return this._json.Meta.VertexCount;
  2322. }
  2323. getNormalizationPositionMinimumValue(physicsSettingIndex) {
  2324. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Position.Minimum;
  2325. }
  2326. getNormalizationPositionMaximumValue(physicsSettingIndex) {
  2327. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Position.Maximum;
  2328. }
  2329. getNormalizationPositionDefaultValue(physicsSettingIndex) {
  2330. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Position.Default;
  2331. }
  2332. getNormalizationAngleMinimumValue(physicsSettingIndex) {
  2333. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Angle.Minimum;
  2334. }
  2335. getNormalizationAngleMaximumValue(physicsSettingIndex) {
  2336. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Angle.Maximum;
  2337. }
  2338. getNormalizationAngleDefaultValue(physicsSettingIndex) {
  2339. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Angle.Default;
  2340. }
  2341. getInputCount(physicsSettingIndex) {
  2342. return this._json.PhysicsSettings[physicsSettingIndex].Input.length;
  2343. }
  2344. getInputWeight(physicsSettingIndex, inputIndex) {
  2345. return this._json.PhysicsSettings[physicsSettingIndex].Input[inputIndex].Weight;
  2346. }
  2347. getInputReflect(physicsSettingIndex, inputIndex) {
  2348. return this._json.PhysicsSettings[physicsSettingIndex].Input[inputIndex].Reflect;
  2349. }
  2350. getInputType(physicsSettingIndex, inputIndex) {
  2351. return this._json.PhysicsSettings[physicsSettingIndex].Input[inputIndex].Type;
  2352. }
  2353. getInputSourceId(physicsSettingIndex, inputIndex) {
  2354. return this._json.PhysicsSettings[physicsSettingIndex].Input[inputIndex].Source.Id;
  2355. }
  2356. getOutputCount(physicsSettingIndex) {
  2357. return this._json.PhysicsSettings[physicsSettingIndex].Output.length;
  2358. }
  2359. getOutputVertexIndex(physicsSettingIndex, outputIndex) {
  2360. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].VertexIndex;
  2361. }
  2362. getOutputAngleScale(physicsSettingIndex, outputIndex) {
  2363. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Scale;
  2364. }
  2365. getOutputWeight(physicsSettingIndex, outputIndex) {
  2366. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Weight;
  2367. }
  2368. getOutputDestinationId(physicsSettingIndex, outputIndex) {
  2369. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Destination.Id;
  2370. }
  2371. getOutputType(physicsSettingIndex, outputIndex) {
  2372. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Type;
  2373. }
  2374. getOutputReflect(physicsSettingIndex, outputIndex) {
  2375. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Reflect;
  2376. }
  2377. getParticleCount(physicsSettingIndex) {
  2378. return this._json.PhysicsSettings[physicsSettingIndex].Vertices.length;
  2379. }
  2380. getParticleMobility(physicsSettingIndex, vertexIndex) {
  2381. return this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Mobility;
  2382. }
  2383. getParticleDelay(physicsSettingIndex, vertexIndex) {
  2384. return this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Delay;
  2385. }
  2386. getParticleAcceleration(physicsSettingIndex, vertexIndex) {
  2387. return this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Acceleration;
  2388. }
  2389. getParticleRadius(physicsSettingIndex, vertexIndex) {
  2390. return this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Radius;
  2391. }
  2392. getParticlePosition(physicsSettingIndex, vertexIndex) {
  2393. const ret = new CubismVector2(0, 0);
  2394. ret.x = this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Position.X;
  2395. ret.y = this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Position.Y;
  2396. return ret;
  2397. }
  2398. };
  2399. var PhysicsTypeTagX = "X";
  2400. var PhysicsTypeTagY = "Y";
  2401. var PhysicsTypeTagAngle = "Angle";
  2402. var AirResistance = 5;
  2403. var MaximumWeight = 100;
  2404. var MovementThreshold = 1e-3;
  2405. var CubismPhysics = class _CubismPhysics {
  2406. static create(json) {
  2407. const ret = new _CubismPhysics();
  2408. ret.parse(json);
  2409. ret._physicsRig.gravity.y = 0;
  2410. return ret;
  2411. }
  2412. evaluate(model, deltaTimeSeconds) {
  2413. let totalAngle;
  2414. let weight;
  2415. let radAngle;
  2416. let outputValue;
  2417. const totalTranslation = new CubismVector2();
  2418. let currentSetting;
  2419. let currentInput;
  2420. let currentOutput;
  2421. let currentParticles;
  2422. let parameterValue;
  2423. let parameterMaximumValue;
  2424. let parameterMinimumValue;
  2425. let parameterDefaultValue;
  2426. parameterValue = model.getModel().parameters.values;
  2427. parameterMaximumValue = model.getModel().parameters.maximumValues;
  2428. parameterMinimumValue = model.getModel().parameters.minimumValues;
  2429. parameterDefaultValue = model.getModel().parameters.defaultValues;
  2430. for (let settingIndex = 0; settingIndex < this._physicsRig.subRigCount; ++settingIndex) {
  2431. totalAngle = { angle: 0 };
  2432. totalTranslation.x = 0;
  2433. totalTranslation.y = 0;
  2434. currentSetting = this._physicsRig.settings[settingIndex];
  2435. currentInput = this._physicsRig.inputs.slice(currentSetting.baseInputIndex);
  2436. currentOutput = this._physicsRig.outputs.slice(currentSetting.baseOutputIndex);
  2437. currentParticles = this._physicsRig.particles.slice(currentSetting.baseParticleIndex);
  2438. for (let i = 0; i < currentSetting.inputCount; ++i) {
  2439. weight = currentInput[i].weight / MaximumWeight;
  2440. if (currentInput[i].sourceParameterIndex == -1) {
  2441. currentInput[i].sourceParameterIndex = model.getParameterIndex(currentInput[i].source.id);
  2442. }
  2443. currentInput[i].getNormalizedParameterValue(totalTranslation, totalAngle, parameterValue[currentInput[i].sourceParameterIndex], parameterMinimumValue[currentInput[i].sourceParameterIndex], parameterMaximumValue[currentInput[i].sourceParameterIndex], parameterDefaultValue[currentInput[i].sourceParameterIndex], currentSetting.normalizationPosition, currentSetting.normalizationAngle, currentInput[i].reflect, weight);
  2444. }
  2445. radAngle = CubismMath.degreesToRadian(-totalAngle.angle);
  2446. totalTranslation.x = totalTranslation.x * CubismMath.cos(radAngle) - totalTranslation.y * CubismMath.sin(radAngle);
  2447. totalTranslation.y = totalTranslation.x * CubismMath.sin(radAngle) + totalTranslation.y * CubismMath.cos(radAngle);
  2448. updateParticles(currentParticles, currentSetting.particleCount, totalTranslation, totalAngle.angle, this._options.wind, MovementThreshold * currentSetting.normalizationPosition.maximum, deltaTimeSeconds, AirResistance);
  2449. for (let i = 0; i < currentSetting.outputCount; ++i) {
  2450. const particleIndex = currentOutput[i].vertexIndex;
  2451. if (particleIndex < 1 || particleIndex >= currentSetting.particleCount) {
  2452. break;
  2453. }
  2454. if (currentOutput[i].destinationParameterIndex == -1) {
  2455. currentOutput[i].destinationParameterIndex = model.getParameterIndex(currentOutput[i].destination.id);
  2456. }
  2457. const translation = new CubismVector2();
  2458. translation.x = currentParticles[particleIndex].position.x - currentParticles[particleIndex - 1].position.x;
  2459. translation.y = currentParticles[particleIndex].position.y - currentParticles[particleIndex - 1].position.y;
  2460. outputValue = currentOutput[i].getValue(translation, currentParticles, particleIndex, currentOutput[i].reflect, this._options.gravity);
  2461. const destinationParameterIndex = currentOutput[i].destinationParameterIndex;
  2462. const outParameterValue = !Float32Array.prototype.slice && "subarray" in Float32Array.prototype ? JSON.parse(JSON.stringify(parameterValue.subarray(destinationParameterIndex))) : parameterValue.slice(destinationParameterIndex);
  2463. updateOutputParameterValue(outParameterValue, parameterMinimumValue[destinationParameterIndex], parameterMaximumValue[destinationParameterIndex], outputValue, currentOutput[i]);
  2464. for (let offset = destinationParameterIndex, outParamIndex = 0; offset < parameterValue.length; offset++, outParamIndex++) {
  2465. parameterValue[offset] = outParameterValue[outParamIndex];
  2466. }
  2467. }
  2468. }
  2469. }
  2470. setOptions(options) {
  2471. this._options = options;
  2472. }
  2473. getOption() {
  2474. return this._options;
  2475. }
  2476. constructor() {
  2477. this._options = new Options();
  2478. this._options.gravity.y = -1;
  2479. this._options.gravity.x = 0;
  2480. this._options.wind.x = 0;
  2481. this._options.wind.y = 0;
  2482. }
  2483. release() {
  2484. this._physicsRig = void 0;
  2485. }
  2486. parse(physicsJson) {
  2487. this._physicsRig = new CubismPhysicsRig();
  2488. let json = new CubismPhysicsJson(physicsJson);
  2489. this._physicsRig.gravity = json.getGravity();
  2490. this._physicsRig.wind = json.getWind();
  2491. this._physicsRig.subRigCount = json.getSubRigCount();
  2492. let inputIndex = 0, outputIndex = 0, particleIndex = 0;
  2493. for (let i = 0; i < this._physicsRig.subRigCount; ++i) {
  2494. const setting = new CubismPhysicsSubRig();
  2495. setting.normalizationPosition.minimum = json.getNormalizationPositionMinimumValue(i);
  2496. setting.normalizationPosition.maximum = json.getNormalizationPositionMaximumValue(i);
  2497. setting.normalizationPosition.defalut = json.getNormalizationPositionDefaultValue(i);
  2498. setting.normalizationAngle.minimum = json.getNormalizationAngleMinimumValue(i);
  2499. setting.normalizationAngle.maximum = json.getNormalizationAngleMaximumValue(i);
  2500. setting.normalizationAngle.defalut = json.getNormalizationAngleDefaultValue(i);
  2501. setting.inputCount = json.getInputCount(i);
  2502. setting.baseInputIndex = inputIndex;
  2503. inputIndex += setting.inputCount;
  2504. for (let j = 0; j < setting.inputCount; ++j) {
  2505. const input = new CubismPhysicsInput();
  2506. input.sourceParameterIndex = -1;
  2507. input.weight = json.getInputWeight(i, j);
  2508. input.reflect = json.getInputReflect(i, j);
  2509. switch (json.getInputType(i, j)) {
  2510. case PhysicsTypeTagX:
  2511. input.type = CubismPhysicsSource.CubismPhysicsSource_X;
  2512. input.getNormalizedParameterValue = getInputTranslationXFromNormalizedParameterValue;
  2513. break;
  2514. case PhysicsTypeTagY:
  2515. input.type = CubismPhysicsSource.CubismPhysicsSource_Y;
  2516. input.getNormalizedParameterValue = getInputTranslationYFromNormalizedParamterValue;
  2517. break;
  2518. case PhysicsTypeTagAngle:
  2519. input.type = CubismPhysicsSource.CubismPhysicsSource_Angle;
  2520. input.getNormalizedParameterValue = getInputAngleFromNormalizedParameterValue;
  2521. break;
  2522. }
  2523. input.source.targetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter;
  2524. input.source.id = json.getInputSourceId(i, j);
  2525. this._physicsRig.inputs.push(input);
  2526. }
  2527. setting.outputCount = json.getOutputCount(i);
  2528. setting.baseOutputIndex = outputIndex;
  2529. outputIndex += setting.outputCount;
  2530. for (let j = 0; j < setting.outputCount; ++j) {
  2531. const output = new CubismPhysicsOutput();
  2532. output.destinationParameterIndex = -1;
  2533. output.vertexIndex = json.getOutputVertexIndex(i, j);
  2534. output.angleScale = json.getOutputAngleScale(i, j);
  2535. output.weight = json.getOutputWeight(i, j);
  2536. output.destination.targetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter;
  2537. output.destination.id = json.getOutputDestinationId(i, j);
  2538. switch (json.getOutputType(i, j)) {
  2539. case PhysicsTypeTagX:
  2540. output.type = CubismPhysicsSource.CubismPhysicsSource_X;
  2541. output.getValue = getOutputTranslationX;
  2542. output.getScale = getOutputScaleTranslationX;
  2543. break;
  2544. case PhysicsTypeTagY:
  2545. output.type = CubismPhysicsSource.CubismPhysicsSource_Y;
  2546. output.getValue = getOutputTranslationY;
  2547. output.getScale = getOutputScaleTranslationY;
  2548. break;
  2549. case PhysicsTypeTagAngle:
  2550. output.type = CubismPhysicsSource.CubismPhysicsSource_Angle;
  2551. output.getValue = getOutputAngle;
  2552. output.getScale = getOutputScaleAngle;
  2553. break;
  2554. }
  2555. output.reflect = json.getOutputReflect(i, j);
  2556. this._physicsRig.outputs.push(output);
  2557. }
  2558. setting.particleCount = json.getParticleCount(i);
  2559. setting.baseParticleIndex = particleIndex;
  2560. particleIndex += setting.particleCount;
  2561. for (let j = 0; j < setting.particleCount; ++j) {
  2562. const particle = new CubismPhysicsParticle();
  2563. particle.mobility = json.getParticleMobility(i, j);
  2564. particle.delay = json.getParticleDelay(i, j);
  2565. particle.acceleration = json.getParticleAcceleration(i, j);
  2566. particle.radius = json.getParticleRadius(i, j);
  2567. particle.position = json.getParticlePosition(i, j);
  2568. this._physicsRig.particles.push(particle);
  2569. }
  2570. this._physicsRig.settings.push(setting);
  2571. }
  2572. this.initialize();
  2573. json.release();
  2574. }
  2575. initialize() {
  2576. let strand;
  2577. let currentSetting;
  2578. let radius;
  2579. for (let settingIndex = 0; settingIndex < this._physicsRig.subRigCount; ++settingIndex) {
  2580. currentSetting = this._physicsRig.settings[settingIndex];
  2581. strand = this._physicsRig.particles.slice(currentSetting.baseParticleIndex);
  2582. strand[0].initialPosition = new CubismVector2(0, 0);
  2583. strand[0].lastPosition = new CubismVector2(strand[0].initialPosition.x, strand[0].initialPosition.y);
  2584. strand[0].lastGravity = new CubismVector2(0, -1);
  2585. strand[0].lastGravity.y *= -1;
  2586. strand[0].velocity = new CubismVector2(0, 0);
  2587. strand[0].force = new CubismVector2(0, 0);
  2588. for (let i = 1; i < currentSetting.particleCount; ++i) {
  2589. radius = new CubismVector2(0, 0);
  2590. radius.y = strand[i].radius;
  2591. strand[i].initialPosition = new CubismVector2(strand[i - 1].initialPosition.x + radius.x, strand[i - 1].initialPosition.y + radius.y);
  2592. strand[i].position = new CubismVector2(strand[i].initialPosition.x, strand[i].initialPosition.y);
  2593. strand[i].lastPosition = new CubismVector2(strand[i].initialPosition.x, strand[i].initialPosition.y);
  2594. strand[i].lastGravity = new CubismVector2(0, -1);
  2595. strand[i].lastGravity.y *= -1;
  2596. strand[i].velocity = new CubismVector2(0, 0);
  2597. strand[i].force = new CubismVector2(0, 0);
  2598. }
  2599. }
  2600. }
  2601. };
  2602. var Options = class {
  2603. constructor() {
  2604. this.gravity = new CubismVector2(0, 0);
  2605. this.wind = new CubismVector2(0, 0);
  2606. }
  2607. };
  2608. function getInputTranslationXFromNormalizedParameterValue(targetTranslation, targetAngle, value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition, normalizationAngle, isInverted, weight) {
  2609. targetTranslation.x += normalizeParameterValue(value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition.minimum, normalizationPosition.maximum, normalizationPosition.defalut, isInverted) * weight;
  2610. }
  2611. function getInputTranslationYFromNormalizedParamterValue(targetTranslation, targetAngle, value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition, normalizationAngle, isInverted, weight) {
  2612. targetTranslation.y += normalizeParameterValue(value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition.minimum, normalizationPosition.maximum, normalizationPosition.defalut, isInverted) * weight;
  2613. }
  2614. function getInputAngleFromNormalizedParameterValue(targetTranslation, targetAngle, value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizaitionPosition, normalizationAngle, isInverted, weight) {
  2615. targetAngle.angle += normalizeParameterValue(value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationAngle.minimum, normalizationAngle.maximum, normalizationAngle.defalut, isInverted) * weight;
  2616. }
  2617. function getOutputTranslationX(translation, particles, particleIndex, isInverted, parentGravity) {
  2618. let outputValue = translation.x;
  2619. if (isInverted) {
  2620. outputValue *= -1;
  2621. }
  2622. return outputValue;
  2623. }
  2624. function getOutputTranslationY(translation, particles, particleIndex, isInverted, parentGravity) {
  2625. let outputValue = translation.y;
  2626. if (isInverted) {
  2627. outputValue *= -1;
  2628. }
  2629. return outputValue;
  2630. }
  2631. function getOutputAngle(translation, particles, particleIndex, isInverted, parentGravity) {
  2632. let outputValue;
  2633. if (particleIndex >= 2) {
  2634. parentGravity = particles[particleIndex - 1].position.substract(particles[particleIndex - 2].position);
  2635. } else {
  2636. parentGravity = parentGravity.multiplyByScaler(-1);
  2637. }
  2638. outputValue = CubismMath.directionToRadian(parentGravity, translation);
  2639. if (isInverted) {
  2640. outputValue *= -1;
  2641. }
  2642. return outputValue;
  2643. }
  2644. function getRangeValue(min, max) {
  2645. return Math.abs(Math.max(min, max) - Math.min(min, max));
  2646. }
  2647. function getDefaultValue(min, max) {
  2648. const minValue = Math.min(min, max);
  2649. return minValue + getRangeValue(min, max) / 2;
  2650. }
  2651. function getOutputScaleTranslationX(translationScale, angleScale) {
  2652. return translationScale.x;
  2653. }
  2654. function getOutputScaleTranslationY(translationScale, angleScale) {
  2655. return translationScale.y;
  2656. }
  2657. function getOutputScaleAngle(translationScale, angleScale) {
  2658. return angleScale;
  2659. }
  2660. function updateParticles(strand, strandCount, totalTranslation, totalAngle, windDirection, thresholdValue, deltaTimeSeconds, airResistance) {
  2661. let totalRadian;
  2662. let delay;
  2663. let radian;
  2664. let currentGravity;
  2665. let direction = new CubismVector2(0, 0);
  2666. let velocity = new CubismVector2(0, 0);
  2667. let force = new CubismVector2(0, 0);
  2668. let newDirection = new CubismVector2(0, 0);
  2669. strand[0].position = new CubismVector2(totalTranslation.x, totalTranslation.y);
  2670. totalRadian = CubismMath.degreesToRadian(totalAngle);
  2671. currentGravity = CubismMath.radianToDirection(totalRadian);
  2672. currentGravity.normalize();
  2673. for (let i = 1; i < strandCount; ++i) {
  2674. strand[i].force = currentGravity.multiplyByScaler(strand[i].acceleration).add(windDirection);
  2675. strand[i].lastPosition = new CubismVector2(strand[i].position.x, strand[i].position.y);
  2676. delay = strand[i].delay * deltaTimeSeconds * 30;
  2677. direction = strand[i].position.substract(strand[i - 1].position);
  2678. radian = CubismMath.directionToRadian(strand[i].lastGravity, currentGravity) / airResistance;
  2679. direction.x = CubismMath.cos(radian) * direction.x - direction.y * CubismMath.sin(radian);
  2680. direction.y = CubismMath.sin(radian) * direction.x + direction.y * CubismMath.cos(radian);
  2681. strand[i].position = strand[i - 1].position.add(direction);
  2682. velocity = strand[i].velocity.multiplyByScaler(delay);
  2683. force = strand[i].force.multiplyByScaler(delay).multiplyByScaler(delay);
  2684. strand[i].position = strand[i].position.add(velocity).add(force);
  2685. newDirection = strand[i].position.substract(strand[i - 1].position);
  2686. newDirection.normalize();
  2687. strand[i].position = strand[i - 1].position.add(newDirection.multiplyByScaler(strand[i].radius));
  2688. if (CubismMath.abs(strand[i].position.x) < thresholdValue) {
  2689. strand[i].position.x = 0;
  2690. }
  2691. if (delay != 0) {
  2692. strand[i].velocity = strand[i].position.substract(strand[i].lastPosition);
  2693. strand[i].velocity = strand[i].velocity.divisionByScalar(delay);
  2694. strand[i].velocity = strand[i].velocity.multiplyByScaler(strand[i].mobility);
  2695. }
  2696. strand[i].force = new CubismVector2(0, 0);
  2697. strand[i].lastGravity = new CubismVector2(currentGravity.x, currentGravity.y);
  2698. }
  2699. }
  2700. function updateOutputParameterValue(parameterValue, parameterValueMinimum, parameterValueMaximum, translation, output) {
  2701. let outputScale;
  2702. let value;
  2703. let weight;
  2704. outputScale = output.getScale(output.translationScale, output.angleScale);
  2705. value = translation * outputScale;
  2706. if (value < parameterValueMinimum) {
  2707. if (value < output.valueBelowMinimum) {
  2708. output.valueBelowMinimum = value;
  2709. }
  2710. value = parameterValueMinimum;
  2711. } else if (value > parameterValueMaximum) {
  2712. if (value > output.valueExceededMaximum) {
  2713. output.valueExceededMaximum = value;
  2714. }
  2715. value = parameterValueMaximum;
  2716. }
  2717. weight = output.weight / MaximumWeight;
  2718. if (weight >= 1) {
  2719. parameterValue[0] = value;
  2720. } else {
  2721. value = parameterValue[0] * (1 - weight) + value * weight;
  2722. parameterValue[0] = value;
  2723. }
  2724. }
  2725. function normalizeParameterValue(value, parameterMinimum, parameterMaximum, parameterDefault, normalizedMinimum, normalizedMaximum, normalizedDefault, isInverted) {
  2726. let result = 0;
  2727. const maxValue = CubismMath.max(parameterMaximum, parameterMinimum);
  2728. if (maxValue < value) {
  2729. value = maxValue;
  2730. }
  2731. const minValue = CubismMath.min(parameterMaximum, parameterMinimum);
  2732. if (minValue > value) {
  2733. value = minValue;
  2734. }
  2735. const minNormValue = CubismMath.min(normalizedMinimum, normalizedMaximum);
  2736. const maxNormValue = CubismMath.max(normalizedMinimum, normalizedMaximum);
  2737. const middleNormValue = normalizedDefault;
  2738. const middleValue = getDefaultValue(minValue, maxValue);
  2739. const paramValue = value - middleValue;
  2740. switch (Math.sign(paramValue)) {
  2741. case 1: {
  2742. const nLength = maxNormValue - middleNormValue;
  2743. const pLength = maxValue - middleValue;
  2744. if (pLength != 0) {
  2745. result = paramValue * (nLength / pLength);
  2746. result += middleNormValue;
  2747. }
  2748. break;
  2749. }
  2750. case -1: {
  2751. const nLength = minNormValue - middleNormValue;
  2752. const pLength = minValue - middleValue;
  2753. if (pLength != 0) {
  2754. result = paramValue * (nLength / pLength);
  2755. result += middleNormValue;
  2756. }
  2757. break;
  2758. }
  2759. case 0: {
  2760. result = middleNormValue;
  2761. break;
  2762. }
  2763. }
  2764. return isInverted ? result : result * -1;
  2765. }
  2766. var csmRect = class {
  2767. constructor(x = 0, y = 0, w = 0, h = 0) {
  2768. this.x = x;
  2769. this.y = y;
  2770. this.width = w;
  2771. this.height = h;
  2772. }
  2773. getCenterX() {
  2774. return this.x + 0.5 * this.width;
  2775. }
  2776. getCenterY() {
  2777. return this.y + 0.5 * this.height;
  2778. }
  2779. getRight() {
  2780. return this.x + this.width;
  2781. }
  2782. getBottom() {
  2783. return this.y + this.height;
  2784. }
  2785. setRect(r) {
  2786. this.x = r.x;
  2787. this.y = r.y;
  2788. this.width = r.width;
  2789. this.height = r.height;
  2790. }
  2791. expand(w, h) {
  2792. this.x -= w;
  2793. this.y -= h;
  2794. this.width += w * 2;
  2795. this.height += h * 2;
  2796. }
  2797. };
  2798. var ColorChannelCount = 4;
  2799. var shaderCount = 10;
  2800. var s_instance;
  2801. var s_viewport;
  2802. var s_fbo;
  2803. var CubismClippingManager_WebGL = class {
  2804. getChannelFlagAsColor(channelNo) {
  2805. return this._channelColors[channelNo];
  2806. }
  2807. getMaskRenderTexture() {
  2808. let ret = 0;
  2809. if (this._maskTexture && this._maskTexture.texture != 0) {
  2810. this._maskTexture.frameNo = this._currentFrameNo;
  2811. ret = this._maskTexture.texture;
  2812. }
  2813. if (ret == 0) {
  2814. const size = this._clippingMaskBufferSize;
  2815. this._colorBuffer = this.gl.createTexture();
  2816. this.gl.bindTexture(this.gl.TEXTURE_2D, this._colorBuffer);
  2817. this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, size, size, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, null);
  2818. this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
  2819. this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
  2820. this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
  2821. this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);
  2822. this.gl.bindTexture(this.gl.TEXTURE_2D, null);
  2823. ret = this.gl.createFramebuffer();
  2824. this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, ret);
  2825. this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, this.gl.COLOR_ATTACHMENT0, this.gl.TEXTURE_2D, this._colorBuffer, 0);
  2826. this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, s_fbo);
  2827. this._maskTexture = new CubismRenderTextureResource(this._currentFrameNo, ret);
  2828. }
  2829. return ret;
  2830. }
  2831. setGL(gl) {
  2832. this.gl = gl;
  2833. }
  2834. calcClippedDrawTotalBounds(model, clippingContext) {
  2835. let clippedDrawTotalMinX = Number.MAX_VALUE;
  2836. let clippedDrawTotalMinY = Number.MAX_VALUE;
  2837. let clippedDrawTotalMaxX = Number.MIN_VALUE;
  2838. let clippedDrawTotalMaxY = Number.MIN_VALUE;
  2839. const clippedDrawCount = clippingContext._clippedDrawableIndexList.length;
  2840. for (let clippedDrawableIndex = 0; clippedDrawableIndex < clippedDrawCount; clippedDrawableIndex++) {
  2841. const drawableIndex = clippingContext._clippedDrawableIndexList[clippedDrawableIndex];
  2842. const drawableVertexCount = model.getDrawableVertexCount(drawableIndex);
  2843. const drawableVertexes = model.getDrawableVertices(drawableIndex);
  2844. let minX = Number.MAX_VALUE;
  2845. let minY = Number.MAX_VALUE;
  2846. let maxX = Number.MIN_VALUE;
  2847. let maxY = Number.MIN_VALUE;
  2848. const loop = drawableVertexCount * Constant.vertexStep;
  2849. for (let pi = Constant.vertexOffset; pi < loop; pi += Constant.vertexStep) {
  2850. const x = drawableVertexes[pi];
  2851. const y = drawableVertexes[pi + 1];
  2852. if (x < minX) {
  2853. minX = x;
  2854. }
  2855. if (x > maxX) {
  2856. maxX = x;
  2857. }
  2858. if (y < minY) {
  2859. minY = y;
  2860. }
  2861. if (y > maxY) {
  2862. maxY = y;
  2863. }
  2864. }
  2865. if (minX == Number.MAX_VALUE) {
  2866. continue;
  2867. }
  2868. if (minX < clippedDrawTotalMinX) {
  2869. clippedDrawTotalMinX = minX;
  2870. }
  2871. if (minY < clippedDrawTotalMinY) {
  2872. clippedDrawTotalMinY = minY;
  2873. }
  2874. if (maxX > clippedDrawTotalMaxX) {
  2875. clippedDrawTotalMaxX = maxX;
  2876. }
  2877. if (maxY > clippedDrawTotalMaxY) {
  2878. clippedDrawTotalMaxY = maxY;
  2879. }
  2880. if (clippedDrawTotalMinX == Number.MAX_VALUE) {
  2881. clippingContext._allClippedDrawRect.x = 0;
  2882. clippingContext._allClippedDrawRect.y = 0;
  2883. clippingContext._allClippedDrawRect.width = 0;
  2884. clippingContext._allClippedDrawRect.height = 0;
  2885. clippingContext._isUsing = false;
  2886. } else {
  2887. clippingContext._isUsing = true;
  2888. const w = clippedDrawTotalMaxX - clippedDrawTotalMinX;
  2889. const h = clippedDrawTotalMaxY - clippedDrawTotalMinY;
  2890. clippingContext._allClippedDrawRect.x = clippedDrawTotalMinX;
  2891. clippingContext._allClippedDrawRect.y = clippedDrawTotalMinY;
  2892. clippingContext._allClippedDrawRect.width = w;
  2893. clippingContext._allClippedDrawRect.height = h;
  2894. }
  2895. }
  2896. }
  2897. constructor() {
  2898. this._maskRenderTexture = null;
  2899. this._colorBuffer = null;
  2900. this._currentFrameNo = 0;
  2901. this._clippingMaskBufferSize = 256;
  2902. this._clippingContextListForMask = [];
  2903. this._clippingContextListForDraw = [];
  2904. this._channelColors = [];
  2905. this._tmpBoundsOnModel = new csmRect();
  2906. this._tmpMatrix = new CubismMatrix44();
  2907. this._tmpMatrixForMask = new CubismMatrix44();
  2908. this._tmpMatrixForDraw = new CubismMatrix44();
  2909. let tmp = new CubismTextureColor();
  2910. tmp.R = 1;
  2911. tmp.G = 0;
  2912. tmp.B = 0;
  2913. tmp.A = 0;
  2914. this._channelColors.push(tmp);
  2915. tmp = new CubismTextureColor();
  2916. tmp.R = 0;
  2917. tmp.G = 1;
  2918. tmp.B = 0;
  2919. tmp.A = 0;
  2920. this._channelColors.push(tmp);
  2921. tmp = new CubismTextureColor();
  2922. tmp.R = 0;
  2923. tmp.G = 0;
  2924. tmp.B = 1;
  2925. tmp.A = 0;
  2926. this._channelColors.push(tmp);
  2927. tmp = new CubismTextureColor();
  2928. tmp.R = 0;
  2929. tmp.G = 0;
  2930. tmp.B = 0;
  2931. tmp.A = 1;
  2932. this._channelColors.push(tmp);
  2933. }
  2934. release() {
  2935. var _a, _b, _c;
  2936. const self = this;
  2937. for (let i = 0; i < this._clippingContextListForMask.length; i++) {
  2938. if (this._clippingContextListForMask[i]) {
  2939. (_a = this._clippingContextListForMask[i]) == null ? void 0 : _a.release();
  2940. }
  2941. }
  2942. self._clippingContextListForMask = void 0;
  2943. self._clippingContextListForDraw = void 0;
  2944. if (this._maskTexture) {
  2945. (_b = this.gl) == null ? void 0 : _b.deleteFramebuffer(this._maskTexture.texture);
  2946. self._maskTexture = void 0;
  2947. }
  2948. self._channelColors = void 0;
  2949. (_c = this.gl) == null ? void 0 : _c.deleteTexture(this._colorBuffer);
  2950. this._colorBuffer = null;
  2951. }
  2952. initialize(model, drawableCount, drawableMasks, drawableMaskCounts) {
  2953. for (let i = 0; i < drawableCount; i++) {
  2954. if (drawableMaskCounts[i] <= 0) {
  2955. this._clippingContextListForDraw.push(null);
  2956. continue;
  2957. }
  2958. let clippingContext = this.findSameClip(drawableMasks[i], drawableMaskCounts[i]);
  2959. if (clippingContext == null) {
  2960. clippingContext = new CubismClippingContext(this, drawableMasks[i], drawableMaskCounts[i]);
  2961. this._clippingContextListForMask.push(clippingContext);
  2962. }
  2963. clippingContext.addClippedDrawable(i);
  2964. this._clippingContextListForDraw.push(clippingContext);
  2965. }
  2966. }
  2967. setupClippingContext(model, renderer) {
  2968. this._currentFrameNo++;
  2969. let usingClipCount = 0;
  2970. for (let clipIndex = 0; clipIndex < this._clippingContextListForMask.length; clipIndex++) {
  2971. const cc = this._clippingContextListForMask[clipIndex];
  2972. this.calcClippedDrawTotalBounds(model, cc);
  2973. if (cc._isUsing) {
  2974. usingClipCount++;
  2975. }
  2976. }
  2977. if (usingClipCount > 0) {
  2978. this.gl.viewport(0, 0, this._clippingMaskBufferSize, this._clippingMaskBufferSize);
  2979. this._maskRenderTexture = this.getMaskRenderTexture();
  2980. renderer.getMvpMatrix();
  2981. renderer.preDraw();
  2982. this.setupLayoutBounds(usingClipCount);
  2983. this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this._maskRenderTexture);
  2984. this.gl.clearColor(1, 1, 1, 1);
  2985. this.gl.clear(this.gl.COLOR_BUFFER_BIT);
  2986. for (let clipIndex = 0; clipIndex < this._clippingContextListForMask.length; clipIndex++) {
  2987. const clipContext = this._clippingContextListForMask[clipIndex];
  2988. const allClipedDrawRect = clipContext._allClippedDrawRect;
  2989. const layoutBoundsOnTex01 = clipContext._layoutBounds;
  2990. const MARGIN = 0.05;
  2991. this._tmpBoundsOnModel.setRect(allClipedDrawRect);
  2992. this._tmpBoundsOnModel.expand(allClipedDrawRect.width * MARGIN, allClipedDrawRect.height * MARGIN);
  2993. const scaleX = layoutBoundsOnTex01.width / this._tmpBoundsOnModel.width;
  2994. const scaleY = layoutBoundsOnTex01.height / this._tmpBoundsOnModel.height;
  2995. {
  2996. this._tmpMatrix.loadIdentity();
  2997. {
  2998. this._tmpMatrix.translateRelative(-1, -1);
  2999. this._tmpMatrix.scaleRelative(2, 2);
  3000. }
  3001. {
  3002. this._tmpMatrix.translateRelative(layoutBoundsOnTex01.x, layoutBoundsOnTex01.y);
  3003. this._tmpMatrix.scaleRelative(scaleX, scaleY);
  3004. this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x, -this._tmpBoundsOnModel.y);
  3005. }
  3006. this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray());
  3007. }
  3008. {
  3009. this._tmpMatrix.loadIdentity();
  3010. {
  3011. this._tmpMatrix.translateRelative(layoutBoundsOnTex01.x, layoutBoundsOnTex01.y);
  3012. this._tmpMatrix.scaleRelative(scaleX, scaleY);
  3013. this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x, -this._tmpBoundsOnModel.y);
  3014. }
  3015. this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray());
  3016. }
  3017. clipContext._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray());
  3018. clipContext._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray());
  3019. const clipDrawCount = clipContext._clippingIdCount;
  3020. for (let i = 0; i < clipDrawCount; i++) {
  3021. const clipDrawIndex = clipContext._clippingIdList[i];
  3022. if (!model.getDrawableDynamicFlagVertexPositionsDidChange(clipDrawIndex)) {
  3023. continue;
  3024. }
  3025. renderer.setIsCulling(model.getDrawableCulling(clipDrawIndex) != false);
  3026. renderer.setClippingContextBufferForMask(clipContext);
  3027. renderer.drawMesh(model.getDrawableTextureIndices(clipDrawIndex), model.getDrawableVertexIndexCount(clipDrawIndex), model.getDrawableVertexCount(clipDrawIndex), model.getDrawableVertexIndices(clipDrawIndex), model.getDrawableVertices(clipDrawIndex), model.getDrawableVertexUvs(clipDrawIndex), model.getDrawableOpacity(clipDrawIndex), CubismBlendMode.CubismBlendMode_Normal, false);
  3028. }
  3029. }
  3030. this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, s_fbo);
  3031. renderer.setClippingContextBufferForMask(null);
  3032. this.gl.viewport(s_viewport[0], s_viewport[1], s_viewport[2], s_viewport[3]);
  3033. }
  3034. }
  3035. findSameClip(drawableMasks, drawableMaskCounts) {
  3036. for (let i = 0; i < this._clippingContextListForMask.length; i++) {
  3037. const clippingContext = this._clippingContextListForMask[i];
  3038. const count = clippingContext._clippingIdCount;
  3039. if (count != drawableMaskCounts) {
  3040. continue;
  3041. }
  3042. let sameCount = 0;
  3043. for (let j = 0; j < count; j++) {
  3044. const clipId = clippingContext._clippingIdList[j];
  3045. for (let k = 0; k < count; k++) {
  3046. if (drawableMasks[k] == clipId) {
  3047. sameCount++;
  3048. break;
  3049. }
  3050. }
  3051. }
  3052. if (sameCount == count) {
  3053. return clippingContext;
  3054. }
  3055. }
  3056. return null;
  3057. }
  3058. setupLayoutBounds(usingClipCount) {
  3059. let div = usingClipCount / ColorChannelCount;
  3060. let mod = usingClipCount % ColorChannelCount;
  3061. div = ~~div;
  3062. mod = ~~mod;
  3063. let curClipIndex = 0;
  3064. for (let channelNo = 0; channelNo < ColorChannelCount; channelNo++) {
  3065. const layoutCount = div + (channelNo < mod ? 1 : 0);
  3066. if (layoutCount == 0)
  3067. ;
  3068. else if (layoutCount == 1) {
  3069. const clipContext = this._clippingContextListForMask[curClipIndex++];
  3070. clipContext._layoutChannelNo = channelNo;
  3071. clipContext._layoutBounds.x = 0;
  3072. clipContext._layoutBounds.y = 0;
  3073. clipContext._layoutBounds.width = 1;
  3074. clipContext._layoutBounds.height = 1;
  3075. } else if (layoutCount == 2) {
  3076. for (let i = 0; i < layoutCount; i++) {
  3077. let xpos = i % 2;
  3078. xpos = ~~xpos;
  3079. const cc = this._clippingContextListForMask[curClipIndex++];
  3080. cc._layoutChannelNo = channelNo;
  3081. cc._layoutBounds.x = xpos * 0.5;
  3082. cc._layoutBounds.y = 0;
  3083. cc._layoutBounds.width = 0.5;
  3084. cc._layoutBounds.height = 1;
  3085. }
  3086. } else if (layoutCount <= 4) {
  3087. for (let i = 0; i < layoutCount; i++) {
  3088. let xpos = i % 2;
  3089. let ypos = i / 2;
  3090. xpos = ~~xpos;
  3091. ypos = ~~ypos;
  3092. const cc = this._clippingContextListForMask[curClipIndex++];
  3093. cc._layoutChannelNo = channelNo;
  3094. cc._layoutBounds.x = xpos * 0.5;
  3095. cc._layoutBounds.y = ypos * 0.5;
  3096. cc._layoutBounds.width = 0.5;
  3097. cc._layoutBounds.height = 0.5;
  3098. }
  3099. } else if (layoutCount <= 9) {
  3100. for (let i = 0; i < layoutCount; i++) {
  3101. let xpos = i % 3;
  3102. let ypos = i / 3;
  3103. xpos = ~~xpos;
  3104. ypos = ~~ypos;
  3105. const cc = this._clippingContextListForMask[curClipIndex++];
  3106. cc._layoutChannelNo = channelNo;
  3107. cc._layoutBounds.x = xpos / 3;
  3108. cc._layoutBounds.y = ypos / 3;
  3109. cc._layoutBounds.width = 1 / 3;
  3110. cc._layoutBounds.height = 1 / 3;
  3111. }
  3112. } else if (CubismConfig.supportMoreMaskDivisions && layoutCount <= 16) {
  3113. for (let i = 0; i < layoutCount; i++) {
  3114. let xpos = i % 4;
  3115. let ypos = i / 4;
  3116. xpos = ~~xpos;
  3117. ypos = ~~ypos;
  3118. const cc = this._clippingContextListForMask[curClipIndex++];
  3119. cc._layoutChannelNo = channelNo;
  3120. cc._layoutBounds.x = xpos / 4;
  3121. cc._layoutBounds.y = ypos / 4;
  3122. cc._layoutBounds.width = 1 / 4;
  3123. cc._layoutBounds.height = 1 / 4;
  3124. }
  3125. } else {
  3126. CubismLogError("not supported mask count : {0}", layoutCount);
  3127. }
  3128. }
  3129. }
  3130. getColorBuffer() {
  3131. return this._colorBuffer;
  3132. }
  3133. getClippingContextListForDraw() {
  3134. return this._clippingContextListForDraw;
  3135. }
  3136. setClippingMaskBufferSize(size) {
  3137. this._clippingMaskBufferSize = size;
  3138. }
  3139. getClippingMaskBufferSize() {
  3140. return this._clippingMaskBufferSize;
  3141. }
  3142. };
  3143. var CubismRenderTextureResource = class {
  3144. constructor(frameNo, texture) {
  3145. this.frameNo = frameNo;
  3146. this.texture = texture;
  3147. }
  3148. };
  3149. var CubismClippingContext = class {
  3150. constructor(manager, clippingDrawableIndices, clipCount) {
  3151. this._isUsing = false;
  3152. this._owner = manager;
  3153. this._clippingIdList = clippingDrawableIndices;
  3154. this._clippingIdCount = clipCount;
  3155. this._allClippedDrawRect = new csmRect();
  3156. this._layoutBounds = new csmRect();
  3157. this._clippedDrawableIndexList = [];
  3158. this._matrixForMask = new CubismMatrix44();
  3159. this._matrixForDraw = new CubismMatrix44();
  3160. }
  3161. release() {
  3162. const self = this;
  3163. self._layoutBounds = void 0;
  3164. self._allClippedDrawRect = void 0;
  3165. self._clippedDrawableIndexList = void 0;
  3166. }
  3167. addClippedDrawable(drawableIndex) {
  3168. this._clippedDrawableIndexList.push(drawableIndex);
  3169. }
  3170. getClippingManager() {
  3171. return this._owner;
  3172. }
  3173. setGl(gl) {
  3174. this._owner.setGL(gl);
  3175. }
  3176. };
  3177. var CubismShader_WebGL = class _CubismShader_WebGL {
  3178. static getInstance() {
  3179. if (s_instance == null) {
  3180. s_instance = new _CubismShader_WebGL();
  3181. return s_instance;
  3182. }
  3183. return s_instance;
  3184. }
  3185. static deleteInstance() {
  3186. if (s_instance) {
  3187. s_instance.release();
  3188. s_instance = void 0;
  3189. }
  3190. }
  3191. constructor() {
  3192. this._shaderSets = [];
  3193. }
  3194. release() {
  3195. this.releaseShaderProgram();
  3196. }
  3197. setupShaderProgram(renderer, textureId, vertexCount, vertexArray, indexArray, uvArray, bufferData, opacity, colorBlendMode, baseColor, isPremultipliedAlpha, matrix4x4, invertedMask) {
  3198. if (!isPremultipliedAlpha) {
  3199. CubismLogError("NoPremultipliedAlpha is not allowed");
  3200. }
  3201. if (this._shaderSets.length == 0) {
  3202. this.generateShaders();
  3203. }
  3204. let SRC_COLOR;
  3205. let DST_COLOR;
  3206. let SRC_ALPHA;
  3207. let DST_ALPHA;
  3208. const clippingContextBufferForMask = renderer.getClippingContextBufferForMask();
  3209. if (clippingContextBufferForMask != null) {
  3210. const shaderSet = this._shaderSets[ShaderNames.ShaderNames_SetupMask];
  3211. this.gl.useProgram(shaderSet.shaderProgram);
  3212. this.gl.activeTexture(this.gl.TEXTURE0);
  3213. this.gl.bindTexture(this.gl.TEXTURE_2D, textureId);
  3214. this.gl.uniform1i(shaderSet.samplerTexture0Location, 0);
  3215. if (bufferData.vertex == null) {
  3216. bufferData.vertex = this.gl.createBuffer();
  3217. }
  3218. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, bufferData.vertex);
  3219. this.gl.bufferData(this.gl.ARRAY_BUFFER, vertexArray, this.gl.DYNAMIC_DRAW);
  3220. this.gl.enableVertexAttribArray(shaderSet.attributePositionLocation);
  3221. this.gl.vertexAttribPointer(shaderSet.attributePositionLocation, 2, this.gl.FLOAT, false, 0, 0);
  3222. if (bufferData.uv == null) {
  3223. bufferData.uv = this.gl.createBuffer();
  3224. }
  3225. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, bufferData.uv);
  3226. this.gl.bufferData(this.gl.ARRAY_BUFFER, uvArray, this.gl.DYNAMIC_DRAW);
  3227. this.gl.enableVertexAttribArray(shaderSet.attributeTexCoordLocation);
  3228. this.gl.vertexAttribPointer(shaderSet.attributeTexCoordLocation, 2, this.gl.FLOAT, false, 0, 0);
  3229. const channelNo = clippingContextBufferForMask._layoutChannelNo;
  3230. const colorChannel = clippingContextBufferForMask.getClippingManager().getChannelFlagAsColor(channelNo);
  3231. this.gl.uniform4f(shaderSet.uniformChannelFlagLocation, colorChannel.R, colorChannel.G, colorChannel.B, colorChannel.A);
  3232. this.gl.uniformMatrix4fv(shaderSet.uniformClipMatrixLocation, false, clippingContextBufferForMask._matrixForMask.getArray());
  3233. const rect = clippingContextBufferForMask._layoutBounds;
  3234. this.gl.uniform4f(shaderSet.uniformBaseColorLocation, rect.x * 2 - 1, rect.y * 2 - 1, rect.getRight() * 2 - 1, rect.getBottom() * 2 - 1);
  3235. SRC_COLOR = this.gl.ZERO;
  3236. DST_COLOR = this.gl.ONE_MINUS_SRC_COLOR;
  3237. SRC_ALPHA = this.gl.ZERO;
  3238. DST_ALPHA = this.gl.ONE_MINUS_SRC_ALPHA;
  3239. } else {
  3240. const clippingContextBufferForDraw = renderer.getClippingContextBufferForDraw();
  3241. const masked = clippingContextBufferForDraw != null;
  3242. const offset = masked ? invertedMask ? 2 : 1 : 0;
  3243. let shaderSet;
  3244. switch (colorBlendMode) {
  3245. case CubismBlendMode.CubismBlendMode_Normal:
  3246. default:
  3247. shaderSet = this._shaderSets[ShaderNames.ShaderNames_NormalPremultipliedAlpha + offset];
  3248. SRC_COLOR = this.gl.ONE;
  3249. DST_COLOR = this.gl.ONE_MINUS_SRC_ALPHA;
  3250. SRC_ALPHA = this.gl.ONE;
  3251. DST_ALPHA = this.gl.ONE_MINUS_SRC_ALPHA;
  3252. break;
  3253. case CubismBlendMode.CubismBlendMode_Additive:
  3254. shaderSet = this._shaderSets[ShaderNames.ShaderNames_AddPremultipliedAlpha + offset];
  3255. SRC_COLOR = this.gl.ONE;
  3256. DST_COLOR = this.gl.ONE;
  3257. SRC_ALPHA = this.gl.ZERO;
  3258. DST_ALPHA = this.gl.ONE;
  3259. break;
  3260. case CubismBlendMode.CubismBlendMode_Multiplicative:
  3261. shaderSet = this._shaderSets[ShaderNames.ShaderNames_MultPremultipliedAlpha + offset];
  3262. SRC_COLOR = this.gl.DST_COLOR;
  3263. DST_COLOR = this.gl.ONE_MINUS_SRC_ALPHA;
  3264. SRC_ALPHA = this.gl.ZERO;
  3265. DST_ALPHA = this.gl.ONE;
  3266. break;
  3267. }
  3268. this.gl.useProgram(shaderSet.shaderProgram);
  3269. if (bufferData.vertex == null) {
  3270. bufferData.vertex = this.gl.createBuffer();
  3271. }
  3272. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, bufferData.vertex);
  3273. this.gl.bufferData(this.gl.ARRAY_BUFFER, vertexArray, this.gl.DYNAMIC_DRAW);
  3274. this.gl.enableVertexAttribArray(shaderSet.attributePositionLocation);
  3275. this.gl.vertexAttribPointer(shaderSet.attributePositionLocation, 2, this.gl.FLOAT, false, 0, 0);
  3276. if (bufferData.uv == null) {
  3277. bufferData.uv = this.gl.createBuffer();
  3278. }
  3279. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, bufferData.uv);
  3280. this.gl.bufferData(this.gl.ARRAY_BUFFER, uvArray, this.gl.DYNAMIC_DRAW);
  3281. this.gl.enableVertexAttribArray(shaderSet.attributeTexCoordLocation);
  3282. this.gl.vertexAttribPointer(shaderSet.attributeTexCoordLocation, 2, this.gl.FLOAT, false, 0, 0);
  3283. if (clippingContextBufferForDraw != null) {
  3284. this.gl.activeTexture(this.gl.TEXTURE1);
  3285. const tex = clippingContextBufferForDraw.getClippingManager().getColorBuffer();
  3286. this.gl.bindTexture(this.gl.TEXTURE_2D, tex);
  3287. this.gl.uniform1i(shaderSet.samplerTexture1Location, 1);
  3288. this.gl.uniformMatrix4fv(shaderSet.uniformClipMatrixLocation, false, clippingContextBufferForDraw._matrixForDraw.getArray());
  3289. const channelNo = clippingContextBufferForDraw._layoutChannelNo;
  3290. const colorChannel = clippingContextBufferForDraw.getClippingManager().getChannelFlagAsColor(channelNo);
  3291. this.gl.uniform4f(shaderSet.uniformChannelFlagLocation, colorChannel.R, colorChannel.G, colorChannel.B, colorChannel.A);
  3292. }
  3293. this.gl.activeTexture(this.gl.TEXTURE0);
  3294. this.gl.bindTexture(this.gl.TEXTURE_2D, textureId);
  3295. this.gl.uniform1i(shaderSet.samplerTexture0Location, 0);
  3296. this.gl.uniformMatrix4fv(shaderSet.uniformMatrixLocation, false, matrix4x4.getArray());
  3297. this.gl.uniform4f(shaderSet.uniformBaseColorLocation, baseColor.R, baseColor.G, baseColor.B, baseColor.A);
  3298. }
  3299. if (bufferData.index == null) {
  3300. bufferData.index = this.gl.createBuffer();
  3301. }
  3302. this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, bufferData.index);
  3303. this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER, indexArray, this.gl.DYNAMIC_DRAW);
  3304. this.gl.blendFuncSeparate(SRC_COLOR, DST_COLOR, SRC_ALPHA, DST_ALPHA);
  3305. }
  3306. releaseShaderProgram() {
  3307. for (let i = 0; i < this._shaderSets.length; i++) {
  3308. this.gl.deleteProgram(this._shaderSets[i].shaderProgram);
  3309. this._shaderSets[i].shaderProgram = 0;
  3310. }
  3311. this._shaderSets = [];
  3312. }
  3313. generateShaders() {
  3314. for (let i = 0; i < shaderCount; i++) {
  3315. this._shaderSets.push({});
  3316. }
  3317. this._shaderSets[0].shaderProgram = this.loadShaderProgram(vertexShaderSrcSetupMask, fragmentShaderSrcsetupMask);
  3318. this._shaderSets[1].shaderProgram = this.loadShaderProgram(vertexShaderSrc, fragmentShaderSrcPremultipliedAlpha);
  3319. this._shaderSets[2].shaderProgram = this.loadShaderProgram(vertexShaderSrcMasked, fragmentShaderSrcMaskPremultipliedAlpha);
  3320. this._shaderSets[3].shaderProgram = this.loadShaderProgram(vertexShaderSrcMasked, fragmentShaderSrcMaskInvertedPremultipliedAlpha);
  3321. this._shaderSets[4].shaderProgram = this._shaderSets[1].shaderProgram;
  3322. this._shaderSets[5].shaderProgram = this._shaderSets[2].shaderProgram;
  3323. this._shaderSets[6].shaderProgram = this._shaderSets[3].shaderProgram;
  3324. this._shaderSets[7].shaderProgram = this._shaderSets[1].shaderProgram;
  3325. this._shaderSets[8].shaderProgram = this._shaderSets[2].shaderProgram;
  3326. this._shaderSets[9].shaderProgram = this._shaderSets[3].shaderProgram;
  3327. this._shaderSets[0].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[0].shaderProgram, "a_position");
  3328. this._shaderSets[0].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[0].shaderProgram, "a_texCoord");
  3329. this._shaderSets[0].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[0].shaderProgram, "s_texture0");
  3330. this._shaderSets[0].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[0].shaderProgram, "u_clipMatrix");
  3331. this._shaderSets[0].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[0].shaderProgram, "u_channelFlag");
  3332. this._shaderSets[0].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[0].shaderProgram, "u_baseColor");
  3333. this._shaderSets[1].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[1].shaderProgram, "a_position");
  3334. this._shaderSets[1].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[1].shaderProgram, "a_texCoord");
  3335. this._shaderSets[1].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[1].shaderProgram, "s_texture0");
  3336. this._shaderSets[1].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[1].shaderProgram, "u_matrix");
  3337. this._shaderSets[1].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[1].shaderProgram, "u_baseColor");
  3338. this._shaderSets[2].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[2].shaderProgram, "a_position");
  3339. this._shaderSets[2].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[2].shaderProgram, "a_texCoord");
  3340. this._shaderSets[2].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "s_texture0");
  3341. this._shaderSets[2].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "s_texture1");
  3342. this._shaderSets[2].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "u_matrix");
  3343. this._shaderSets[2].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "u_clipMatrix");
  3344. this._shaderSets[2].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "u_channelFlag");
  3345. this._shaderSets[2].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "u_baseColor");
  3346. this._shaderSets[3].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[3].shaderProgram, "a_position");
  3347. this._shaderSets[3].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[3].shaderProgram, "a_texCoord");
  3348. this._shaderSets[3].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "s_texture0");
  3349. this._shaderSets[3].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "s_texture1");
  3350. this._shaderSets[3].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "u_matrix");
  3351. this._shaderSets[3].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "u_clipMatrix");
  3352. this._shaderSets[3].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "u_channelFlag");
  3353. this._shaderSets[3].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "u_baseColor");
  3354. this._shaderSets[4].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[4].shaderProgram, "a_position");
  3355. this._shaderSets[4].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[4].shaderProgram, "a_texCoord");
  3356. this._shaderSets[4].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[4].shaderProgram, "s_texture0");
  3357. this._shaderSets[4].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[4].shaderProgram, "u_matrix");
  3358. this._shaderSets[4].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[4].shaderProgram, "u_baseColor");
  3359. this._shaderSets[5].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[5].shaderProgram, "a_position");
  3360. this._shaderSets[5].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[5].shaderProgram, "a_texCoord");
  3361. this._shaderSets[5].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "s_texture0");
  3362. this._shaderSets[5].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "s_texture1");
  3363. this._shaderSets[5].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "u_matrix");
  3364. this._shaderSets[5].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "u_clipMatrix");
  3365. this._shaderSets[5].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "u_channelFlag");
  3366. this._shaderSets[5].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "u_baseColor");
  3367. this._shaderSets[6].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[6].shaderProgram, "a_position");
  3368. this._shaderSets[6].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[6].shaderProgram, "a_texCoord");
  3369. this._shaderSets[6].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "s_texture0");
  3370. this._shaderSets[6].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "s_texture1");
  3371. this._shaderSets[6].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "u_matrix");
  3372. this._shaderSets[6].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "u_clipMatrix");
  3373. this._shaderSets[6].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "u_channelFlag");
  3374. this._shaderSets[6].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "u_baseColor");
  3375. this._shaderSets[7].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[7].shaderProgram, "a_position");
  3376. this._shaderSets[7].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[7].shaderProgram, "a_texCoord");
  3377. this._shaderSets[7].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[7].shaderProgram, "s_texture0");
  3378. this._shaderSets[7].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[7].shaderProgram, "u_matrix");
  3379. this._shaderSets[7].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[7].shaderProgram, "u_baseColor");
  3380. this._shaderSets[8].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[8].shaderProgram, "a_position");
  3381. this._shaderSets[8].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[8].shaderProgram, "a_texCoord");
  3382. this._shaderSets[8].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "s_texture0");
  3383. this._shaderSets[8].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "s_texture1");
  3384. this._shaderSets[8].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "u_matrix");
  3385. this._shaderSets[8].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "u_clipMatrix");
  3386. this._shaderSets[8].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "u_channelFlag");
  3387. this._shaderSets[8].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "u_baseColor");
  3388. this._shaderSets[9].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[9].shaderProgram, "a_position");
  3389. this._shaderSets[9].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[9].shaderProgram, "a_texCoord");
  3390. this._shaderSets[9].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "s_texture0");
  3391. this._shaderSets[9].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "s_texture1");
  3392. this._shaderSets[9].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "u_matrix");
  3393. this._shaderSets[9].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "u_clipMatrix");
  3394. this._shaderSets[9].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "u_channelFlag");
  3395. this._shaderSets[9].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "u_baseColor");
  3396. }
  3397. loadShaderProgram(vertexShaderSource, fragmentShaderSource) {
  3398. let shaderProgram = this.gl.createProgram();
  3399. let vertShader = this.compileShaderSource(this.gl.VERTEX_SHADER, vertexShaderSource);
  3400. if (!vertShader) {
  3401. CubismLogError("Vertex shader compile error!");
  3402. return 0;
  3403. }
  3404. let fragShader = this.compileShaderSource(this.gl.FRAGMENT_SHADER, fragmentShaderSource);
  3405. if (!fragShader) {
  3406. CubismLogError("Vertex shader compile error!");
  3407. return 0;
  3408. }
  3409. this.gl.attachShader(shaderProgram, vertShader);
  3410. this.gl.attachShader(shaderProgram, fragShader);
  3411. this.gl.linkProgram(shaderProgram);
  3412. const linkStatus = this.gl.getProgramParameter(shaderProgram, this.gl.LINK_STATUS);
  3413. if (!linkStatus) {
  3414. CubismLogError("Failed to link program: {0}", shaderProgram);
  3415. this.gl.deleteShader(vertShader);
  3416. this.gl.deleteShader(fragShader);
  3417. if (shaderProgram) {
  3418. this.gl.deleteProgram(shaderProgram);
  3419. }
  3420. return 0;
  3421. }
  3422. this.gl.deleteShader(vertShader);
  3423. this.gl.deleteShader(fragShader);
  3424. return shaderProgram;
  3425. }
  3426. compileShaderSource(shaderType, shaderSource) {
  3427. const source = shaderSource;
  3428. const shader = this.gl.createShader(shaderType);
  3429. this.gl.shaderSource(shader, source);
  3430. this.gl.compileShader(shader);
  3431. if (!shader) {
  3432. const log = this.gl.getShaderInfoLog(shader);
  3433. CubismLogError("Shader compile log: {0} ", log);
  3434. }
  3435. const status = this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS);
  3436. if (!status) {
  3437. this.gl.deleteShader(shader);
  3438. return null;
  3439. }
  3440. return shader;
  3441. }
  3442. setGl(gl) {
  3443. this.gl = gl;
  3444. }
  3445. };
  3446. var ShaderNames = ((ShaderNames2) => {
  3447. ShaderNames2[ShaderNames2["ShaderNames_SetupMask"] = 0] = "ShaderNames_SetupMask";
  3448. ShaderNames2[ShaderNames2["ShaderNames_NormalPremultipliedAlpha"] = 1] = "ShaderNames_NormalPremultipliedAlpha";
  3449. ShaderNames2[ShaderNames2["ShaderNames_NormalMaskedPremultipliedAlpha"] = 2] = "ShaderNames_NormalMaskedPremultipliedAlpha";
  3450. ShaderNames2[ShaderNames2["ShaderNames_NomralMaskedInvertedPremultipliedAlpha"] = 3] = "ShaderNames_NomralMaskedInvertedPremultipliedAlpha";
  3451. ShaderNames2[ShaderNames2["ShaderNames_AddPremultipliedAlpha"] = 4] = "ShaderNames_AddPremultipliedAlpha";
  3452. ShaderNames2[ShaderNames2["ShaderNames_AddMaskedPremultipliedAlpha"] = 5] = "ShaderNames_AddMaskedPremultipliedAlpha";
  3453. ShaderNames2[ShaderNames2["ShaderNames_AddMaskedPremultipliedAlphaInverted"] = 6] = "ShaderNames_AddMaskedPremultipliedAlphaInverted";
  3454. ShaderNames2[ShaderNames2["ShaderNames_MultPremultipliedAlpha"] = 7] = "ShaderNames_MultPremultipliedAlpha";
  3455. ShaderNames2[ShaderNames2["ShaderNames_MultMaskedPremultipliedAlpha"] = 8] = "ShaderNames_MultMaskedPremultipliedAlpha";
  3456. ShaderNames2[ShaderNames2["ShaderNames_MultMaskedPremultipliedAlphaInverted"] = 9] = "ShaderNames_MultMaskedPremultipliedAlphaInverted";
  3457. return ShaderNames2;
  3458. })(ShaderNames || {});
  3459. var vertexShaderSrcSetupMask = "attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}";
  3460. var fragmentShaderSrcsetupMask = "precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}";
  3461. var vertexShaderSrc = "attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}";
  3462. var vertexShaderSrcMasked = "attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}";
  3463. var fragmentShaderSrcPremultipliedAlpha = "precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;void main(){ gl_FragColor = texture2D(s_texture0 , v_texCoord) * u_baseColor;}";
  3464. var fragmentShaderSrcMaskPremultipliedAlpha = "precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;void main(){ vec4 col_formask = texture2D(s_texture0 , v_texCoord) * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}";
  3465. var fragmentShaderSrcMaskInvertedPremultipliedAlpha = "precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;void main(){vec4 col_formask = texture2D(s_texture0, v_texCoord) * u_baseColor;vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;col_formask = col_formask * (1.0 - maskVal);gl_FragColor = col_formask;}";
  3466. var CubismRenderer_WebGL = class extends CubismRenderer {
  3467. constructor() {
  3468. super();
  3469. this._clippingContextBufferForMask = null;
  3470. this._clippingContextBufferForDraw = null;
  3471. this._clippingManager = new CubismClippingManager_WebGL();
  3472. this.firstDraw = true;
  3473. this._textures = {};
  3474. this._sortedDrawableIndexList = [];
  3475. this._bufferData = {
  3476. vertex: null,
  3477. uv: null,
  3478. index: null
  3479. };
  3480. }
  3481. initialize(model) {
  3482. if (model.isUsingMasking()) {
  3483. this._clippingManager = new CubismClippingManager_WebGL();
  3484. this._clippingManager.initialize(model, model.getDrawableCount(), model.getDrawableMasks(), model.getDrawableMaskCounts());
  3485. }
  3486. for (let i = model.getDrawableCount() - 1; i >= 0; i--) {
  3487. this._sortedDrawableIndexList[i] = 0;
  3488. }
  3489. super.initialize(model);
  3490. }
  3491. bindTexture(modelTextureNo, glTexture) {
  3492. this._textures[modelTextureNo] = glTexture;
  3493. }
  3494. getBindedTextures() {
  3495. return this._textures;
  3496. }
  3497. setClippingMaskBufferSize(size) {
  3498. this._clippingManager.release();
  3499. this._clippingManager = new CubismClippingManager_WebGL();
  3500. this._clippingManager.setClippingMaskBufferSize(size);
  3501. this._clippingManager.initialize(this.getModel(), this.getModel().getDrawableCount(), this.getModel().getDrawableMasks(), this.getModel().getDrawableMaskCounts());
  3502. }
  3503. getClippingMaskBufferSize() {
  3504. return this._clippingManager.getClippingMaskBufferSize();
  3505. }
  3506. release() {
  3507. var _a, _b, _c;
  3508. const self = this;
  3509. this._clippingManager.release();
  3510. self._clippingManager = void 0;
  3511. (_a = this.gl) == null ? void 0 : _a.deleteBuffer(this._bufferData.vertex);
  3512. this._bufferData.vertex = null;
  3513. (_b = this.gl) == null ? void 0 : _b.deleteBuffer(this._bufferData.uv);
  3514. this._bufferData.uv = null;
  3515. (_c = this.gl) == null ? void 0 : _c.deleteBuffer(this._bufferData.index);
  3516. this._bufferData.index = null;
  3517. self._bufferData = void 0;
  3518. self._textures = void 0;
  3519. }
  3520. doDrawModel() {
  3521. this.preDraw();
  3522. if (this._clippingManager != null) {
  3523. this._clippingManager.setupClippingContext(this.getModel(), this);
  3524. }
  3525. const drawableCount = this.getModel().getDrawableCount();
  3526. const renderOrder = this.getModel().getDrawableRenderOrders();
  3527. for (let i = 0; i < drawableCount; ++i) {
  3528. const order = renderOrder[i];
  3529. this._sortedDrawableIndexList[order] = i;
  3530. }
  3531. for (let i = 0; i < drawableCount; ++i) {
  3532. const drawableIndex = this._sortedDrawableIndexList[i];
  3533. if (!this.getModel().getDrawableDynamicFlagIsVisible(drawableIndex)) {
  3534. continue;
  3535. }
  3536. this.setClippingContextBufferForDraw(this._clippingManager != null ? this._clippingManager.getClippingContextListForDraw()[drawableIndex] : null);
  3537. this.setIsCulling(this.getModel().getDrawableCulling(drawableIndex));
  3538. this.drawMesh(this.getModel().getDrawableTextureIndices(drawableIndex), this.getModel().getDrawableVertexIndexCount(drawableIndex), this.getModel().getDrawableVertexCount(drawableIndex), this.getModel().getDrawableVertexIndices(drawableIndex), this.getModel().getDrawableVertices(drawableIndex), this.getModel().getDrawableVertexUvs(drawableIndex), this.getModel().getDrawableOpacity(drawableIndex), this.getModel().getDrawableBlendMode(drawableIndex), this.getModel().getDrawableInvertedMaskBit(drawableIndex));
  3539. }
  3540. }
  3541. drawMesh(textureNo, indexCount, vertexCount, indexArray, vertexArray, uvArray, opacity, colorBlendMode, invertedMask) {
  3542. if (this.isCulling()) {
  3543. this.gl.enable(this.gl.CULL_FACE);
  3544. } else {
  3545. this.gl.disable(this.gl.CULL_FACE);
  3546. }
  3547. this.gl.frontFace(this.gl.CCW);
  3548. const modelColorRGBA = this.getModelColor();
  3549. if (this.getClippingContextBufferForMask() == null) {
  3550. modelColorRGBA.A *= opacity;
  3551. if (this.isPremultipliedAlpha()) {
  3552. modelColorRGBA.R *= modelColorRGBA.A;
  3553. modelColorRGBA.G *= modelColorRGBA.A;
  3554. modelColorRGBA.B *= modelColorRGBA.A;
  3555. }
  3556. }
  3557. let drawtexture = null;
  3558. if (this._textures[textureNo] != null) {
  3559. drawtexture = this._textures[textureNo];
  3560. }
  3561. CubismShader_WebGL.getInstance().setupShaderProgram(this, drawtexture, vertexCount, vertexArray, indexArray, uvArray, this._bufferData, opacity, colorBlendMode, modelColorRGBA, this.isPremultipliedAlpha(), this.getMvpMatrix(), invertedMask);
  3562. this.gl.drawElements(this.gl.TRIANGLES, indexCount, this.gl.UNSIGNED_SHORT, 0);
  3563. this.gl.useProgram(null);
  3564. this.setClippingContextBufferForDraw(null);
  3565. this.setClippingContextBufferForMask(null);
  3566. }
  3567. static doStaticRelease() {
  3568. CubismShader_WebGL.deleteInstance();
  3569. }
  3570. setRenderState(fbo, viewport) {
  3571. s_fbo = fbo;
  3572. s_viewport = viewport;
  3573. }
  3574. preDraw() {
  3575. if (this.firstDraw) {
  3576. this.firstDraw = false;
  3577. this._anisortopy = this.gl.getExtension("EXT_texture_filter_anisotropic") || this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") || this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic");
  3578. }
  3579. this.gl.disable(this.gl.SCISSOR_TEST);
  3580. this.gl.disable(this.gl.STENCIL_TEST);
  3581. this.gl.disable(this.gl.DEPTH_TEST);
  3582. this.gl.frontFace(this.gl.CW);
  3583. this.gl.enable(this.gl.BLEND);
  3584. this.gl.colorMask(true, true, true, true);
  3585. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);
  3586. this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, null);
  3587. }
  3588. setClippingContextBufferForMask(clip) {
  3589. this._clippingContextBufferForMask = clip;
  3590. }
  3591. getClippingContextBufferForMask() {
  3592. return this._clippingContextBufferForMask;
  3593. }
  3594. setClippingContextBufferForDraw(clip) {
  3595. this._clippingContextBufferForDraw = clip;
  3596. }
  3597. getClippingContextBufferForDraw() {
  3598. return this._clippingContextBufferForDraw;
  3599. }
  3600. startUp(gl) {
  3601. this.gl = gl;
  3602. this._clippingManager.setGL(gl);
  3603. CubismShader_WebGL.getInstance().setGl(gl);
  3604. }
  3605. };
  3606. CubismRenderer.staticRelease = () => {
  3607. CubismRenderer_WebGL.doStaticRelease();
  3608. };
  3609. var CubismModelSettingsJson = class {
  3610. constructor(json) {
  3611. this.groups = json.Groups;
  3612. this.hitAreas = json.HitAreas;
  3613. this.layout = json.Layout;
  3614. this.moc = json.FileReferences.Moc;
  3615. this.expressions = json.FileReferences.Expressions;
  3616. this.motions = json.FileReferences.Motions;
  3617. this.textures = json.FileReferences.Textures;
  3618. this.physics = json.FileReferences.Physics;
  3619. this.pose = json.FileReferences.Pose;
  3620. }
  3621. getEyeBlinkParameters() {
  3622. var _a, _b;
  3623. return (_b = (_a = this.groups) == null ? void 0 : _a.find((group) => group.Name === "EyeBlink")) == null ? void 0 : _b.Ids;
  3624. }
  3625. getLipSyncParameters() {
  3626. var _a, _b;
  3627. return (_b = (_a = this.groups) == null ? void 0 : _a.find((group) => group.Name === "LipSync")) == null ? void 0 : _b.Ids;
  3628. }
  3629. };
  3630. var HitAreaPrefix = "HitArea";
  3631. var HitAreaHead = "Head";
  3632. var HitAreaBody = "Body";
  3633. var PartsIdCore = "Parts01Core";
  3634. var PartsArmPrefix = "Parts01Arm_";
  3635. var PartsArmLPrefix = "Parts01ArmL_";
  3636. var PartsArmRPrefix = "Parts01ArmR_";
  3637. var ParamAngleX = "ParamAngleX";
  3638. var ParamAngleY = "ParamAngleY";
  3639. var ParamAngleZ = "ParamAngleZ";
  3640. var ParamEyeLOpen = "ParamEyeLOpen";
  3641. var ParamEyeLSmile = "ParamEyeLSmile";
  3642. var ParamEyeROpen = "ParamEyeROpen";
  3643. var ParamEyeRSmile = "ParamEyeRSmile";
  3644. var ParamEyeBallX = "ParamEyeBallX";
  3645. var ParamEyeBallY = "ParamEyeBallY";
  3646. var ParamEyeBallForm = "ParamEyeBallForm";
  3647. var ParamBrowLY = "ParamBrowLY";
  3648. var ParamBrowRY = "ParamBrowRY";
  3649. var ParamBrowLX = "ParamBrowLX";
  3650. var ParamBrowRX = "ParamBrowRX";
  3651. var ParamBrowLAngle = "ParamBrowLAngle";
  3652. var ParamBrowRAngle = "ParamBrowRAngle";
  3653. var ParamBrowLForm = "ParamBrowLForm";
  3654. var ParamBrowRForm = "ParamBrowRForm";
  3655. var ParamMouthForm = "ParamMouthForm";
  3656. var ParamMouthOpenY = "ParamMouthOpenY";
  3657. var ParamCheek = "ParamCheek";
  3658. var ParamBodyAngleX = "ParamBodyAngleX";
  3659. var ParamBodyAngleY = "ParamBodyAngleY";
  3660. var ParamBodyAngleZ = "ParamBodyAngleZ";
  3661. var ParamBreath = "ParamBreath";
  3662. var ParamArmLA = "ParamArmLA";
  3663. var ParamArmRA = "ParamArmRA";
  3664. var ParamArmLB = "ParamArmLB";
  3665. var ParamArmRB = "ParamArmRB";
  3666. var ParamHandL = "ParamHandL";
  3667. var ParamHandR = "ParamHandR";
  3668. var ParamHairFront = "ParamHairFront";
  3669. var ParamHairSide = "ParamHairSide";
  3670. var ParamHairBack = "ParamHairBack";
  3671. var ParamHairFluffy = "ParamHairFluffy";
  3672. var ParamShoulderY = "ParamShoulderY";
  3673. var ParamBustX = "ParamBustX";
  3674. var ParamBustY = "ParamBustY";
  3675. var ParamBaseX = "ParamBaseX";
  3676. var ParamBaseY = "ParamBaseY";
  3677. var ParamNONE = "NONE:";
  3678. var LOGICAL_WIDTH = 2;
  3679. var LOGICAL_HEIGHT = 2;
  3680. var config;
  3681. ((config2) => {
  3682. config2.LOG_LEVEL_VERBOSE = 0;
  3683. config2.LOG_LEVEL_WARNING = 1;
  3684. config2.LOG_LEVEL_ERROR = 2;
  3685. config2.LOG_LEVEL_NONE = 999;
  3686. config2.logLevel = config2.LOG_LEVEL_WARNING;
  3687. config2.sound = true;
  3688. config2.motionSync = true;
  3689. config2.motionFadingDuration = 500;
  3690. config2.idleMotionFadingDuration = 2e3;
  3691. config2.expressionFadingDuration = 500;
  3692. config2.preserveExpressionOnMotion = true;
  3693. config2.cubism4 = CubismConfig;
  3694. })(config || (config = {}));
  3695. var VERSION = "0.4.0";
  3696. var logger = {
  3697. log(tag, ...messages) {
  3698. if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
  3699. console.log(`[${tag}]`, ...messages);
  3700. }
  3701. },
  3702. warn(tag, ...messages) {
  3703. if (config.logLevel <= config.LOG_LEVEL_WARNING) {
  3704. console.warn(`[${tag}]`, ...messages);
  3705. }
  3706. },
  3707. error(tag, ...messages) {
  3708. if (config.logLevel <= config.LOG_LEVEL_ERROR) {
  3709. console.error(`[${tag}]`, ...messages);
  3710. }
  3711. }
  3712. };
  3713. function clamp(num, lower, upper) {
  3714. return num < lower ? lower : num > upper ? upper : num;
  3715. }
  3716. function rand(min, max) {
  3717. return Math.random() * (max - min) + min;
  3718. }
  3719. function copyProperty(type, from, to, fromKey, toKey) {
  3720. const value = from[fromKey];
  3721. if (value !== null && typeof value === type) {
  3722. to[toKey] = value;
  3723. }
  3724. }
  3725. function copyArray(type, from, to, fromKey, toKey) {
  3726. const array = from[fromKey];
  3727. if (Array.isArray(array)) {
  3728. to[toKey] = array.filter((item) => item !== null && typeof item === type);
  3729. }
  3730. }
  3731. function applyMixins(derivedCtor, baseCtors) {
  3732. baseCtors.forEach((baseCtor) => {
  3733. Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
  3734. if (name !== "constructor") {
  3735. Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
  3736. }
  3737. });
  3738. });
  3739. }
  3740. function folderName(url2) {
  3741. let lastSlashIndex = url2.lastIndexOf("/");
  3742. if (lastSlashIndex != -1) {
  3743. url2 = url2.slice(0, lastSlashIndex);
  3744. }
  3745. lastSlashIndex = url2.lastIndexOf("/");
  3746. if (lastSlashIndex !== -1) {
  3747. url2 = url2.slice(lastSlashIndex + 1);
  3748. }
  3749. return url2;
  3750. }
  3751. function remove(array, item) {
  3752. const index = array.indexOf(item);
  3753. if (index !== -1) {
  3754. array.splice(index, 1);
  3755. }
  3756. }
  3757. var ExpressionManager = class extends import_eventemitter3.default {
  3758. constructor(settings, options) {
  3759. super();
  3760. this.expressions = [];
  3761. this.reserveExpressionIndex = -1;
  3762. this.destroyed = false;
  3763. this.settings = settings;
  3764. this.tag = `ExpressionManager(${settings.name})`;
  3765. }
  3766. init() {
  3767. this.defaultExpression = this.createExpression({}, void 0);
  3768. this.currentExpression = this.defaultExpression;
  3769. this.stopAllExpressions();
  3770. }
  3771. loadExpression(index) {
  3772. return __async(this, null, function* () {
  3773. if (!this.definitions[index]) {
  3774. logger.warn(this.tag, `Undefined expression at [${index}]`);
  3775. return void 0;
  3776. }
  3777. if (this.expressions[index] === null) {
  3778. logger.warn(this.tag, `Cannot set expression at [${index}] because it's already failed in loading.`);
  3779. return void 0;
  3780. }
  3781. if (this.expressions[index]) {
  3782. return this.expressions[index];
  3783. }
  3784. const expression = yield this._loadExpression(index);
  3785. this.expressions[index] = expression;
  3786. return expression;
  3787. });
  3788. }
  3789. _loadExpression(index) {
  3790. throw new Error("Not implemented.");
  3791. }
  3792. setRandomExpression() {
  3793. return __async(this, null, function* () {
  3794. if (this.definitions.length) {
  3795. const availableIndices = [];
  3796. for (let i = 0; i < this.definitions.length; i++) {
  3797. if (this.expressions[i] !== null && this.expressions[i] !== this.currentExpression && i !== this.reserveExpressionIndex) {
  3798. availableIndices.push(i);
  3799. }
  3800. }
  3801. if (availableIndices.length) {
  3802. const index = Math.floor(Math.random() * availableIndices.length);
  3803. return this.setExpression(index);
  3804. }
  3805. }
  3806. return false;
  3807. });
  3808. }
  3809. resetExpression() {
  3810. this._setExpression(this.defaultExpression);
  3811. }
  3812. restoreExpression() {
  3813. this._setExpression(this.currentExpression);
  3814. }
  3815. setExpression(index) {
  3816. return __async(this, null, function* () {
  3817. if (typeof index !== "number") {
  3818. index = this.getExpressionIndex(index);
  3819. }
  3820. if (!(index > -1 && index < this.definitions.length)) {
  3821. return false;
  3822. }
  3823. if (index === this.expressions.indexOf(this.currentExpression)) {
  3824. return false;
  3825. }
  3826. this.reserveExpressionIndex = index;
  3827. const expression = yield this.loadExpression(index);
  3828. if (!expression || this.reserveExpressionIndex !== index) {
  3829. return false;
  3830. }
  3831. this.reserveExpressionIndex = -1;
  3832. this.currentExpression = expression;
  3833. this._setExpression(expression);
  3834. return true;
  3835. });
  3836. }
  3837. update(model, now) {
  3838. if (!this.isFinished()) {
  3839. return this.updateParameters(model, now);
  3840. }
  3841. return false;
  3842. }
  3843. destroy() {
  3844. this.destroyed = true;
  3845. this.emit("destroy");
  3846. const self = this;
  3847. self.definitions = void 0;
  3848. self.expressions = void 0;
  3849. }
  3850. };
  3851. var EPSILON = 0.01;
  3852. var MAX_SPEED = 40 / 7.5;
  3853. var ACCELERATION_TIME = 1 / (0.15 * 1e3);
  3854. var FocusController = class {
  3855. constructor() {
  3856. this.targetX = 0;
  3857. this.targetY = 0;
  3858. this.x = 0;
  3859. this.y = 0;
  3860. this.vx = 0;
  3861. this.vy = 0;
  3862. }
  3863. focus(x, y, instant = false) {
  3864. this.targetX = clamp(x, -1, 1);
  3865. this.targetY = clamp(y, -1, 1);
  3866. if (instant) {
  3867. this.x = this.targetX;
  3868. this.y = this.targetY;
  3869. }
  3870. }
  3871. update(dt) {
  3872. const dx = this.targetX - this.x;
  3873. const dy = this.targetY - this.y;
  3874. if (Math.abs(dx) < EPSILON && Math.abs(dy) < EPSILON)
  3875. return;
  3876. const d = Math.sqrt(__pow(dx, 2) + __pow(dy, 2));
  3877. const maxSpeed = MAX_SPEED / (1e3 / dt);
  3878. let ax = maxSpeed * (dx / d) - this.vx;
  3879. let ay = maxSpeed * (dy / d) - this.vy;
  3880. const a = Math.sqrt(__pow(ax, 2) + __pow(ay, 2));
  3881. const maxA = maxSpeed * ACCELERATION_TIME * dt;
  3882. if (a > maxA) {
  3883. ax *= maxA / a;
  3884. ay *= maxA / a;
  3885. }
  3886. this.vx += ax;
  3887. this.vy += ay;
  3888. const v = Math.sqrt(__pow(this.vx, 2) + __pow(this.vy, 2));
  3889. const maxV = 0.5 * (Math.sqrt(__pow(maxA, 2) + 8 * maxA * d) - maxA);
  3890. if (v > maxV) {
  3891. this.vx *= maxV / v;
  3892. this.vy *= maxV / v;
  3893. }
  3894. this.x += this.vx;
  3895. this.y += this.vy;
  3896. }
  3897. };
  3898. var ModelSettings = class {
  3899. constructor(json) {
  3900. this.json = json;
  3901. let url2 = json.url;
  3902. if (typeof url2 !== "string") {
  3903. throw new TypeError("The `url` field in settings JSON must be defined as a string.");
  3904. }
  3905. this.url = url2;
  3906. this.name = folderName(this.url);
  3907. }
  3908. resolveURL(path) {
  3909. return url.resolve(this.url, path);
  3910. }
  3911. replaceFiles(replacer) {
  3912. this.moc = replacer(this.moc, "moc");
  3913. if (this.pose !== void 0) {
  3914. this.pose = replacer(this.pose, "pose");
  3915. }
  3916. if (this.physics !== void 0) {
  3917. this.physics = replacer(this.physics, "physics");
  3918. }
  3919. for (let i = 0; i < this.textures.length; i++) {
  3920. this.textures[i] = replacer(this.textures[i], `textures[${i}]`);
  3921. }
  3922. }
  3923. getDefinedFiles() {
  3924. const files = [];
  3925. this.replaceFiles((file) => {
  3926. files.push(file);
  3927. return file;
  3928. });
  3929. return files;
  3930. }
  3931. validateFiles(files) {
  3932. const assertFileExists = (expectedFile, shouldThrow) => {
  3933. const actualPath = this.resolveURL(expectedFile);
  3934. if (!files.includes(actualPath)) {
  3935. if (shouldThrow) {
  3936. throw new Error(`File "${expectedFile}" is defined in settings, but doesn't exist in given files`);
  3937. }
  3938. return false;
  3939. }
  3940. return true;
  3941. };
  3942. const essentialFiles = [this.moc, ...this.textures];
  3943. essentialFiles.forEach((texture) => assertFileExists(texture, true));
  3944. const definedFiles = this.getDefinedFiles();
  3945. return definedFiles.filter((file) => assertFileExists(file, false));
  3946. }
  3947. };
  3948. var MotionPriority = ((MotionPriority2) => {
  3949. MotionPriority2[MotionPriority2["NONE"] = 0] = "NONE";
  3950. MotionPriority2[MotionPriority2["IDLE"] = 1] = "IDLE";
  3951. MotionPriority2[MotionPriority2["NORMAL"] = 2] = "NORMAL";
  3952. MotionPriority2[MotionPriority2["FORCE"] = 3] = "FORCE";
  3953. return MotionPriority2;
  3954. })(MotionPriority || {});
  3955. var MotionState = class {
  3956. constructor() {
  3957. this.debug = false;
  3958. this.currentPriority = 0;
  3959. this.reservePriority = 0;
  3960. }
  3961. reserve(group, index, priority) {
  3962. if (priority <= 0) {
  3963. logger.log(this.tag, `Cannot start a motion with MotionPriority.NONE.`);
  3964. return false;
  3965. }
  3966. if (group === this.currentGroup && index === this.currentIndex) {
  3967. logger.log(this.tag, `Motion is already playing.`, this.dump(group, index));
  3968. return false;
  3969. }
  3970. if (group === this.reservedGroup && index === this.reservedIndex || group === this.reservedIdleGroup && index === this.reservedIdleIndex) {
  3971. logger.log(this.tag, `Motion is already reserved.`, this.dump(group, index));
  3972. return false;
  3973. }
  3974. if (priority === 1) {
  3975. if (this.currentPriority !== 0) {
  3976. logger.log(this.tag, `Cannot start idle motion because another motion is playing.`, this.dump(group, index));
  3977. return false;
  3978. }
  3979. if (this.reservedIdleGroup !== void 0) {
  3980. logger.log(this.tag, `Cannot start idle motion because another idle motion has reserved.`, this.dump(group, index));
  3981. return false;
  3982. }
  3983. this.setReservedIdle(group, index);
  3984. } else {
  3985. if (priority < 3) {
  3986. if (priority <= this.currentPriority) {
  3987. logger.log(this.tag, "Cannot start motion because another motion is playing as an equivalent or higher priority.", this.dump(group, index));
  3988. return false;
  3989. }
  3990. if (priority <= this.reservePriority) {
  3991. logger.log(this.tag, "Cannot start motion because another motion has reserved as an equivalent or higher priority.", this.dump(group, index));
  3992. return false;
  3993. }
  3994. }
  3995. this.setReserved(group, index, priority);
  3996. }
  3997. return true;
  3998. }
  3999. start(motion, group, index, priority) {
  4000. if (priority === 1) {
  4001. this.setReservedIdle(void 0, void 0);
  4002. if (this.currentPriority !== 0) {
  4003. logger.log(this.tag, "Cannot start idle motion because another motion is playing.", this.dump(group, index));
  4004. return false;
  4005. }
  4006. } else {
  4007. if (group !== this.reservedGroup || index !== this.reservedIndex) {
  4008. logger.log(this.tag, "Cannot start motion because another motion has taken the place.", this.dump(group, index));
  4009. return false;
  4010. }
  4011. this.setReserved(void 0, void 0, 0);
  4012. }
  4013. if (!motion) {
  4014. return false;
  4015. }
  4016. this.setCurrent(group, index, priority);
  4017. return true;
  4018. }
  4019. complete() {
  4020. this.setCurrent(void 0, void 0, 0);
  4021. }
  4022. setCurrent(group, index, priority) {
  4023. this.currentPriority = priority;
  4024. this.currentGroup = group;
  4025. this.currentIndex = index;
  4026. }
  4027. setReserved(group, index, priority) {
  4028. this.reservePriority = priority;
  4029. this.reservedGroup = group;
  4030. this.reservedIndex = index;
  4031. }
  4032. setReservedIdle(group, index) {
  4033. this.reservedIdleGroup = group;
  4034. this.reservedIdleIndex = index;
  4035. }
  4036. isActive(group, index) {
  4037. return group === this.currentGroup && index === this.currentIndex || group === this.reservedGroup && index === this.reservedIndex || group === this.reservedIdleGroup && index === this.reservedIdleIndex;
  4038. }
  4039. reset() {
  4040. this.setCurrent(void 0, void 0, 0);
  4041. this.setReserved(void 0, void 0, 0);
  4042. this.setReservedIdle(void 0, void 0);
  4043. }
  4044. shouldRequestIdleMotion() {
  4045. return this.currentGroup === void 0 && this.reservedIdleGroup === void 0;
  4046. }
  4047. shouldOverrideExpression() {
  4048. return !config.preserveExpressionOnMotion && this.currentPriority > 1;
  4049. }
  4050. dump(requestedGroup, requestedIndex) {
  4051. if (this.debug) {
  4052. const keys = [
  4053. "currentPriority",
  4054. "reservePriority",
  4055. "currentGroup",
  4056. "currentIndex",
  4057. "reservedGroup",
  4058. "reservedIndex",
  4059. "reservedIdleGroup",
  4060. "reservedIdleIndex"
  4061. ];
  4062. return `
  4063. <Requested> group = "${requestedGroup}", index = ${requestedIndex}
  4064. ` + keys.map((key) => "[" + key + "] " + this[key]).join("\n");
  4065. }
  4066. return "";
  4067. }
  4068. };
  4069. var TAG$2 = "SoundManager";
  4070. var VOLUME = 0.5;
  4071. var SoundManager = class {
  4072. static get volume() {
  4073. return this._volume;
  4074. }
  4075. static set volume(value) {
  4076. this._volume = (value > 1 ? 1 : value < 0 ? 0 : value) || 0;
  4077. this.audios.forEach((audio) => audio.volume = this._volume);
  4078. }
  4079. static add(file, onFinish, onError) {
  4080. const audio = new Audio(file);
  4081. audio.volume = this._volume;
  4082. audio.preload = "auto";
  4083. audio.addEventListener("ended", () => {
  4084. this.dispose(audio);
  4085. onFinish == null ? void 0 : onFinish();
  4086. });
  4087. audio.addEventListener("error", (e) => {
  4088. this.dispose(audio);
  4089. logger.warn(TAG$2, `Error occurred on "${file}"`, e.error);
  4090. onError == null ? void 0 : onError(e.error);
  4091. });
  4092. this.audios.push(audio);
  4093. return audio;
  4094. }
  4095. static play(audio) {
  4096. return new Promise((resolve, reject) => {
  4097. var _a;
  4098. (_a = audio.play()) == null ? void 0 : _a.catch((e) => {
  4099. audio.dispatchEvent(new ErrorEvent("error", { error: e }));
  4100. reject(e);
  4101. });
  4102. if (audio.readyState === audio.HAVE_ENOUGH_DATA) {
  4103. resolve();
  4104. } else {
  4105. audio.addEventListener("canplaythrough", resolve);
  4106. }
  4107. });
  4108. }
  4109. static dispose(audio) {
  4110. audio.pause();
  4111. audio.removeAttribute("src");
  4112. remove(this.audios, audio);
  4113. }
  4114. static destroy() {
  4115. for (let i = this.audios.length - 1; i >= 0; i--) {
  4116. this.dispose(this.audios[i]);
  4117. }
  4118. }
  4119. };
  4120. SoundManager.audios = [];
  4121. SoundManager._volume = VOLUME;
  4122. var MotionPreloadStrategy = ((MotionPreloadStrategy2) => {
  4123. MotionPreloadStrategy2["ALL"] = "ALL";
  4124. MotionPreloadStrategy2["IDLE"] = "IDLE";
  4125. MotionPreloadStrategy2["NONE"] = "NONE";
  4126. return MotionPreloadStrategy2;
  4127. })(MotionPreloadStrategy || {});
  4128. var MotionManager = class extends import_eventemitter3.default {
  4129. constructor(settings, options) {
  4130. super();
  4131. this.motionGroups = {};
  4132. this.state = new MotionState();
  4133. this.playing = false;
  4134. this.destroyed = false;
  4135. this.settings = settings;
  4136. this.tag = `MotionManager(${settings.name})`;
  4137. this.state.tag = this.tag;
  4138. }
  4139. init(options) {
  4140. if (options == null ? void 0 : options.idleMotionGroup) {
  4141. this.groups.idle = options.idleMotionGroup;
  4142. }
  4143. this.setupMotions(options);
  4144. this.stopAllMotions();
  4145. }
  4146. setupMotions(options) {
  4147. for (const group of Object.keys(this.definitions)) {
  4148. this.motionGroups[group] = [];
  4149. }
  4150. let groups;
  4151. switch (options == null ? void 0 : options.motionPreload) {
  4152. case "NONE":
  4153. return;
  4154. case "ALL":
  4155. groups = Object.keys(this.definitions);
  4156. break;
  4157. case "IDLE":
  4158. default:
  4159. groups = [this.groups.idle];
  4160. break;
  4161. }
  4162. for (const group of groups) {
  4163. if (this.definitions[group]) {
  4164. for (let i = 0; i < this.definitions[group].length; i++) {
  4165. this.loadMotion(group, i).then();
  4166. }
  4167. }
  4168. }
  4169. }
  4170. loadMotion(group, index) {
  4171. return __async(this, null, function* () {
  4172. var _a;
  4173. if (!((_a = this.definitions[group]) == null ? void 0 : _a[index])) {
  4174. logger.warn(this.tag, `Undefined motion at "${group}"[${index}]`);
  4175. return void 0;
  4176. }
  4177. if (this.motionGroups[group][index] === null) {
  4178. logger.warn(this.tag, `Cannot start motion at "${group}"[${index}] because it's already failed in loading.`);
  4179. return void 0;
  4180. }
  4181. if (this.motionGroups[group][index]) {
  4182. return this.motionGroups[group][index];
  4183. }
  4184. const motion = yield this._loadMotion(group, index);
  4185. if (this.destroyed) {
  4186. return;
  4187. }
  4188. this.motionGroups[group][index] = motion != null ? motion : null;
  4189. return motion;
  4190. });
  4191. }
  4192. _loadMotion(group, index) {
  4193. throw new Error("Not implemented.");
  4194. }
  4195. startMotion(_0, _1) {
  4196. return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL) {
  4197. var _a;
  4198. if (!this.state.reserve(group, index, priority)) {
  4199. return false;
  4200. }
  4201. const definition = (_a = this.definitions[group]) == null ? void 0 : _a[index];
  4202. if (!definition) {
  4203. return false;
  4204. }
  4205. if (this.currentAudio) {
  4206. SoundManager.dispose(this.currentAudio);
  4207. }
  4208. let audio;
  4209. if (config.sound) {
  4210. const soundURL = this.getSoundFile(definition);
  4211. if (soundURL) {
  4212. try {
  4213. audio = SoundManager.add(this.settings.resolveURL(soundURL), () => this.currentAudio = void 0, () => this.currentAudio = void 0);
  4214. this.currentAudio = audio;
  4215. } catch (e) {
  4216. logger.warn(this.tag, "Failed to create audio", soundURL, e);
  4217. }
  4218. }
  4219. }
  4220. const motion = yield this.loadMotion(group, index);
  4221. if (audio) {
  4222. const readyToPlay = SoundManager.play(audio).catch((e) => logger.warn(this.tag, "Failed to play audio", audio.src, e));
  4223. if (config.motionSync) {
  4224. yield readyToPlay;
  4225. }
  4226. }
  4227. if (!this.state.start(motion, group, index, priority)) {
  4228. if (audio) {
  4229. SoundManager.dispose(audio);
  4230. this.currentAudio = void 0;
  4231. }
  4232. return false;
  4233. }
  4234. logger.log(this.tag, "Start motion:", this.getMotionName(definition));
  4235. this.emit("motionStart", group, index, audio);
  4236. if (this.state.shouldOverrideExpression()) {
  4237. this.expressionManager && this.expressionManager.resetExpression();
  4238. }
  4239. this.playing = true;
  4240. this._startMotion(motion);
  4241. return true;
  4242. });
  4243. }
  4244. startRandomMotion(group, priority) {
  4245. return __async(this, null, function* () {
  4246. const groupDefs = this.definitions[group];
  4247. if (groupDefs == null ? void 0 : groupDefs.length) {
  4248. const availableIndices = [];
  4249. for (let i = 0; i < groupDefs.length; i++) {
  4250. if (this.motionGroups[group][i] !== null && !this.state.isActive(group, i)) {
  4251. availableIndices.push(i);
  4252. }
  4253. }
  4254. if (availableIndices.length) {
  4255. const index = Math.floor(Math.random() * availableIndices.length);
  4256. return this.startMotion(group, availableIndices[index], priority);
  4257. }
  4258. }
  4259. return false;
  4260. });
  4261. }
  4262. stopAllMotions() {
  4263. this._stopAllMotions();
  4264. this.state.reset();
  4265. if (this.currentAudio) {
  4266. SoundManager.dispose(this.currentAudio);
  4267. this.currentAudio = void 0;
  4268. }
  4269. }
  4270. update(model, now) {
  4271. var _a;
  4272. if (this.isFinished()) {
  4273. if (this.playing) {
  4274. this.playing = false;
  4275. this.emit("motionFinish");
  4276. }
  4277. if (this.state.shouldOverrideExpression()) {
  4278. (_a = this.expressionManager) == null ? void 0 : _a.restoreExpression();
  4279. }
  4280. this.state.complete();
  4281. if (this.state.shouldRequestIdleMotion()) {
  4282. this.startRandomMotion(this.groups.idle, MotionPriority.IDLE);
  4283. }
  4284. }
  4285. return this.updateParameters(model, now);
  4286. }
  4287. destroy() {
  4288. var _a;
  4289. this.destroyed = true;
  4290. this.emit("destroy");
  4291. this.stopAllMotions();
  4292. (_a = this.expressionManager) == null ? void 0 : _a.destroy();
  4293. const self = this;
  4294. self.definitions = void 0;
  4295. self.motionGroups = void 0;
  4296. }
  4297. };
  4298. var tempBounds = { x: 0, y: 0, width: 0, height: 0 };
  4299. var InternalModel = class extends import_eventemitter3.default {
  4300. constructor() {
  4301. super(...arguments);
  4302. this.focusController = new FocusController();
  4303. this.originalWidth = 0;
  4304. this.originalHeight = 0;
  4305. this.width = 0;
  4306. this.height = 0;
  4307. this.localTransform = new Matrix();
  4308. this.drawingMatrix = new Matrix();
  4309. this.hitAreas = {};
  4310. this.textureFlipY = false;
  4311. this.viewport = [0, 0, 0, 0];
  4312. this.destroyed = false;
  4313. }
  4314. init() {
  4315. this.setupLayout();
  4316. this.setupHitAreas();
  4317. }
  4318. setupLayout() {
  4319. const self = this;
  4320. const size = this.getSize();
  4321. self.originalWidth = size[0];
  4322. self.originalHeight = size[1];
  4323. const layout = Object.assign({
  4324. width: LOGICAL_WIDTH,
  4325. height: LOGICAL_HEIGHT
  4326. }, this.getLayout());
  4327. this.localTransform.scale(layout.width / LOGICAL_WIDTH, layout.height / LOGICAL_HEIGHT);
  4328. self.width = this.originalWidth * this.localTransform.a;
  4329. self.height = this.originalHeight * this.localTransform.d;
  4330. 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;
  4331. 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;
  4332. this.localTransform.translate(this.width * offsetX, -this.height * offsetY);
  4333. }
  4334. setupHitAreas() {
  4335. const definitions = this.getHitAreaDefs().filter((hitArea) => hitArea.index >= 0);
  4336. for (const def of definitions) {
  4337. this.hitAreas[def.name] = def;
  4338. }
  4339. }
  4340. hitTest(x, y) {
  4341. return Object.keys(this.hitAreas).filter((hitAreaName) => this.isHit(hitAreaName, x, y));
  4342. }
  4343. isHit(hitAreaName, x, y) {
  4344. if (!this.hitAreas[hitAreaName]) {
  4345. return false;
  4346. }
  4347. const drawIndex = this.hitAreas[hitAreaName].index;
  4348. const bounds = this.getDrawableBounds(drawIndex, tempBounds);
  4349. return bounds.x <= x && x <= bounds.x + bounds.width && bounds.y <= y && y <= bounds.y + bounds.height;
  4350. }
  4351. getDrawableBounds(index, bounds) {
  4352. const vertices = this.getDrawableVertices(index);
  4353. let left = vertices[0];
  4354. let right = vertices[0];
  4355. let top = vertices[1];
  4356. let bottom = vertices[1];
  4357. for (let i = 0; i < vertices.length; i += 2) {
  4358. const vx = vertices[i];
  4359. const vy = vertices[i + 1];
  4360. left = Math.min(vx, left);
  4361. right = Math.max(vx, right);
  4362. top = Math.min(vy, top);
  4363. bottom = Math.max(vy, bottom);
  4364. }
  4365. bounds != null ? bounds : bounds = {};
  4366. bounds.x = left;
  4367. bounds.y = top;
  4368. bounds.width = right - left;
  4369. bounds.height = bottom - top;
  4370. return bounds;
  4371. }
  4372. updateTransform(transform) {
  4373. this.drawingMatrix.copyFrom(transform).append(this.localTransform);
  4374. }
  4375. update(dt, now) {
  4376. this.focusController.update(dt);
  4377. }
  4378. destroy() {
  4379. this.destroyed = true;
  4380. this.emit("destroy");
  4381. this.motionManager.destroy();
  4382. this.motionManager = void 0;
  4383. }
  4384. };
  4385. var TAG$1 = "XHRLoader";
  4386. var NetworkError = class extends Error {
  4387. constructor(message, url2, status, aborted = false) {
  4388. super(message);
  4389. this.url = url2;
  4390. this.status = status;
  4391. this.aborted = aborted;
  4392. }
  4393. };
  4394. var _XHRLoader = class {
  4395. static createXHR(target, url2, type, onload, onerror) {
  4396. const xhr = new XMLHttpRequest();
  4397. _XHRLoader.allXhrSet.add(xhr);
  4398. if (target) {
  4399. let xhrSet = _XHRLoader.xhrMap.get(target);
  4400. if (!xhrSet) {
  4401. xhrSet = /* @__PURE__ */ new Set([xhr]);
  4402. _XHRLoader.xhrMap.set(target, xhrSet);
  4403. } else {
  4404. xhrSet.add(xhr);
  4405. }
  4406. if (!target.listeners("destroy").includes(_XHRLoader.cancelXHRs)) {
  4407. target.once("destroy", _XHRLoader.cancelXHRs);
  4408. }
  4409. }
  4410. xhr.open("GET", url2);
  4411. xhr.responseType = type;
  4412. xhr.onload = () => {
  4413. if ((xhr.status === 200 || xhr.status === 0) && xhr.response) {
  4414. onload(xhr.response);
  4415. } else {
  4416. xhr.onerror();
  4417. }
  4418. };
  4419. xhr.onerror = () => {
  4420. logger.warn(TAG$1, `Failed to load resource as ${xhr.responseType} (Status ${xhr.status}): ${url2}`);
  4421. onerror(new NetworkError("Network error.", url2, xhr.status));
  4422. };
  4423. xhr.onabort = () => onerror(new NetworkError("Aborted.", url2, xhr.status, true));
  4424. xhr.onloadend = () => {
  4425. var _a;
  4426. _XHRLoader.allXhrSet.delete(xhr);
  4427. if (target) {
  4428. (_a = _XHRLoader.xhrMap.get(target)) == null ? void 0 : _a.delete(xhr);
  4429. }
  4430. };
  4431. return xhr;
  4432. }
  4433. static cancelXHRs() {
  4434. var _a;
  4435. (_a = _XHRLoader.xhrMap.get(this)) == null ? void 0 : _a.forEach((xhr) => {
  4436. xhr.abort();
  4437. _XHRLoader.allXhrSet.delete(xhr);
  4438. });
  4439. _XHRLoader.xhrMap.delete(this);
  4440. }
  4441. static release() {
  4442. _XHRLoader.allXhrSet.forEach((xhr) => xhr.abort());
  4443. _XHRLoader.allXhrSet.clear();
  4444. _XHRLoader.xhrMap = /* @__PURE__ */ new WeakMap();
  4445. }
  4446. };
  4447. var XHRLoader = _XHRLoader;
  4448. XHRLoader.xhrMap = /* @__PURE__ */ new WeakMap();
  4449. XHRLoader.allXhrSet = /* @__PURE__ */ new Set();
  4450. XHRLoader.loader = (context, next) => {
  4451. return new Promise((resolve, reject) => {
  4452. const xhr = _XHRLoader.createXHR(context.target, context.settings ? context.settings.resolveURL(context.url) : context.url, context.type, (data) => {
  4453. context.result = data;
  4454. resolve();
  4455. }, reject);
  4456. xhr.send();
  4457. });
  4458. };
  4459. function runMiddlewares(middleware, context) {
  4460. let index = -1;
  4461. return dispatch(0);
  4462. function dispatch(i, err) {
  4463. if (err)
  4464. return Promise.reject(err);
  4465. if (i <= index)
  4466. return Promise.reject(new Error("next() called multiple times"));
  4467. index = i;
  4468. const fn = middleware[i];
  4469. if (!fn)
  4470. return Promise.resolve();
  4471. try {
  4472. return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
  4473. } catch (err2) {
  4474. return Promise.reject(err2);
  4475. }
  4476. }
  4477. }
  4478. var Live2DLoader = class {
  4479. static load(context) {
  4480. return runMiddlewares(this.middlewares, context).then(() => context.result);
  4481. }
  4482. };
  4483. Live2DLoader.middlewares = [XHRLoader.loader];
  4484. function createTexture(url2, options = {}) {
  4485. var _a;
  4486. const textureOptions = { resourceOptions: { crossorigin: options.crossOrigin } };
  4487. if (Texture.fromURL) {
  4488. return Texture.fromURL(url2, textureOptions).catch((e) => {
  4489. if (e instanceof Error) {
  4490. throw e;
  4491. }
  4492. const err = new Error("Texture loading error");
  4493. err.event = e;
  4494. throw err;
  4495. });
  4496. }
  4497. textureOptions.resourceOptions.autoLoad = false;
  4498. const texture = Texture.from(url2, textureOptions);
  4499. if (texture.baseTexture.valid) {
  4500. return Promise.resolve(texture);
  4501. }
  4502. const resource = texture.baseTexture.resource;
  4503. (_a = resource._live2d_load) != null ? _a : resource._live2d_load = new Promise((resolve, reject) => {
  4504. const errorHandler = (event) => {
  4505. resource.source.removeEventListener("error", errorHandler);
  4506. const err = new Error("Texture loading error");
  4507. err.event = event;
  4508. reject(err);
  4509. };
  4510. resource.source.addEventListener("error", errorHandler);
  4511. resource.load().then(() => resolve(texture)).catch(errorHandler);
  4512. });
  4513. return resource._live2d_load;
  4514. }
  4515. var TAG = "Live2DFactory";
  4516. var urlToJSON = (context, next) => __async(void 0, null, function* () {
  4517. if (typeof context.source === "string") {
  4518. const data = yield Live2DLoader.load({
  4519. url: context.source,
  4520. type: "json",
  4521. target: context.live2dModel
  4522. });
  4523. data.url = context.source;
  4524. context.source = data;
  4525. context.live2dModel.emit("settingsJSONLoaded", data);
  4526. }
  4527. return next();
  4528. });
  4529. var jsonToSettings = (context, next) => __async(void 0, null, function* () {
  4530. if (context.source instanceof ModelSettings) {
  4531. context.settings = context.source;
  4532. return next();
  4533. } else if (typeof context.source === "object") {
  4534. const runtime = Live2DFactory.findRuntime(context.source);
  4535. if (runtime) {
  4536. const settings = runtime.createModelSettings(context.source);
  4537. context.settings = settings;
  4538. context.live2dModel.emit("settingsLoaded", settings);
  4539. return next();
  4540. }
  4541. }
  4542. throw new TypeError("Unknown settings format.");
  4543. });
  4544. var waitUntilReady = (context, next) => {
  4545. if (context.settings) {
  4546. const runtime = Live2DFactory.findRuntime(context.settings);
  4547. if (runtime) {
  4548. return runtime.ready().then(next);
  4549. }
  4550. }
  4551. return next();
  4552. };
  4553. var setupOptionals = (context, next) => __async(void 0, null, function* () {
  4554. yield next();
  4555. const internalModel = context.internalModel;
  4556. if (internalModel) {
  4557. const settings = context.settings;
  4558. const runtime = Live2DFactory.findRuntime(settings);
  4559. if (runtime) {
  4560. const tasks = [];
  4561. if (settings.pose) {
  4562. tasks.push(Live2DLoader.load({
  4563. settings,
  4564. url: settings.pose,
  4565. type: "json",
  4566. target: internalModel
  4567. }).then((data) => {
  4568. internalModel.pose = runtime.createPose(internalModel.coreModel, data);
  4569. context.live2dModel.emit("poseLoaded", internalModel.pose);
  4570. }).catch((e) => {
  4571. context.live2dModel.emit("poseLoadError", e);
  4572. logger.warn(TAG, "Failed to load pose.", e);
  4573. }));
  4574. }
  4575. if (settings.physics) {
  4576. tasks.push(Live2DLoader.load({
  4577. settings,
  4578. url: settings.physics,
  4579. type: "json",
  4580. target: internalModel
  4581. }).then((data) => {
  4582. internalModel.physics = runtime.createPhysics(internalModel.coreModel, data);
  4583. context.live2dModel.emit("physicsLoaded", internalModel.physics);
  4584. }).catch((e) => {
  4585. context.live2dModel.emit("physicsLoadError", e);
  4586. logger.warn(TAG, "Failed to load physics.", e);
  4587. }));
  4588. }
  4589. if (tasks.length) {
  4590. yield Promise.all(tasks);
  4591. }
  4592. }
  4593. }
  4594. });
  4595. var setupEssentials = (context, next) => __async(void 0, null, function* () {
  4596. if (context.settings) {
  4597. const live2DModel = context.live2dModel;
  4598. const textureLoadings = context.settings.textures.map((tex) => {
  4599. const url2 = context.settings.resolveURL(tex);
  4600. return createTexture(url2, { crossOrigin: context.options.crossOrigin });
  4601. });
  4602. yield next();
  4603. if (context.internalModel) {
  4604. live2DModel.internalModel = context.internalModel;
  4605. live2DModel.emit("modelLoaded", context.internalModel);
  4606. } else {
  4607. throw new TypeError("Missing internal model.");
  4608. }
  4609. live2DModel.textures = yield Promise.all(textureLoadings);
  4610. live2DModel.emit("textureLoaded", live2DModel.textures);
  4611. } else {
  4612. throw new TypeError("Missing settings.");
  4613. }
  4614. });
  4615. var createInternalModel = (context, next) => __async(void 0, null, function* () {
  4616. const settings = context.settings;
  4617. if (settings instanceof ModelSettings) {
  4618. const runtime = Live2DFactory.findRuntime(settings);
  4619. if (!runtime) {
  4620. throw new TypeError("Unknown model settings.");
  4621. }
  4622. const modelData = yield Live2DLoader.load({
  4623. settings,
  4624. url: settings.moc,
  4625. type: "arraybuffer",
  4626. target: context.live2dModel
  4627. });
  4628. if (!runtime.isValidMoc(modelData)) {
  4629. throw new Error("Invalid moc data");
  4630. }
  4631. const coreModel = runtime.createCoreModel(modelData);
  4632. context.internalModel = runtime.createInternalModel(coreModel, settings, context.options);
  4633. return next();
  4634. }
  4635. throw new TypeError("Missing settings.");
  4636. });
  4637. var _Live2DFactory = class {
  4638. static registerRuntime(runtime) {
  4639. _Live2DFactory.runtimes.push(runtime);
  4640. _Live2DFactory.runtimes.sort((a, b) => b.version - a.version);
  4641. }
  4642. static findRuntime(source) {
  4643. for (const runtime of _Live2DFactory.runtimes) {
  4644. if (runtime.test(source)) {
  4645. return runtime;
  4646. }
  4647. }
  4648. }
  4649. static setupLive2DModel(live2dModel, source, options) {
  4650. return __async(this, null, function* () {
  4651. const textureLoaded = new Promise((resolve) => live2dModel.once("textureLoaded", resolve));
  4652. const modelLoaded = new Promise((resolve) => live2dModel.once("modelLoaded", resolve));
  4653. const readyEventEmitted = Promise.all([textureLoaded, modelLoaded]).then(() => live2dModel.emit("ready"));
  4654. yield runMiddlewares(_Live2DFactory.live2DModelMiddlewares, {
  4655. live2dModel,
  4656. source,
  4657. options: options || {}
  4658. });
  4659. yield readyEventEmitted;
  4660. live2dModel.emit("load");
  4661. });
  4662. }
  4663. static loadMotion(motionManager, group, index) {
  4664. var _a, _b;
  4665. const handleError = (e) => motionManager.emit("motionLoadError", group, index, e);
  4666. try {
  4667. const definition = (_a = motionManager.definitions[group]) == null ? void 0 : _a[index];
  4668. if (!definition) {
  4669. return Promise.resolve(void 0);
  4670. }
  4671. if (!motionManager.listeners("destroy").includes(_Live2DFactory.releaseTasks)) {
  4672. motionManager.once("destroy", _Live2DFactory.releaseTasks);
  4673. }
  4674. let tasks = _Live2DFactory.motionTasksMap.get(motionManager);
  4675. if (!tasks) {
  4676. tasks = {};
  4677. _Live2DFactory.motionTasksMap.set(motionManager, tasks);
  4678. }
  4679. let taskGroup = tasks[group];
  4680. if (!taskGroup) {
  4681. taskGroup = [];
  4682. tasks[group] = taskGroup;
  4683. }
  4684. const path = motionManager.getMotionFile(definition);
  4685. (_b = taskGroup[index]) != null ? _b : taskGroup[index] = Live2DLoader.load({
  4686. url: path,
  4687. settings: motionManager.settings,
  4688. type: motionManager.motionDataType,
  4689. target: motionManager
  4690. }).then((data) => {
  4691. var _a2;
  4692. const taskGroup2 = (_a2 = _Live2DFactory.motionTasksMap.get(motionManager)) == null ? void 0 : _a2[group];
  4693. if (taskGroup2) {
  4694. delete taskGroup2[index];
  4695. }
  4696. const motion = motionManager.createMotion(data, group, definition);
  4697. motionManager.emit("motionLoaded", group, index, motion);
  4698. return motion;
  4699. }).catch((e) => {
  4700. logger.warn(motionManager.tag, `Failed to load motion: ${path}
  4701. `, e);
  4702. handleError(e);
  4703. });
  4704. return taskGroup[index];
  4705. } catch (e) {
  4706. logger.warn(motionManager.tag, `Failed to load motion at "${group}"[${index}]
  4707. `, e);
  4708. handleError(e);
  4709. }
  4710. return Promise.resolve(void 0);
  4711. }
  4712. static loadExpression(expressionManager, index) {
  4713. var _a;
  4714. const handleError = (e) => expressionManager.emit("expressionLoadError", index, e);
  4715. try {
  4716. const definition = expressionManager.definitions[index];
  4717. if (!definition) {
  4718. return Promise.resolve(void 0);
  4719. }
  4720. if (!expressionManager.listeners("destroy").includes(_Live2DFactory.releaseTasks)) {
  4721. expressionManager.once("destroy", _Live2DFactory.releaseTasks);
  4722. }
  4723. let tasks = _Live2DFactory.expressionTasksMap.get(expressionManager);
  4724. if (!tasks) {
  4725. tasks = [];
  4726. _Live2DFactory.expressionTasksMap.set(expressionManager, tasks);
  4727. }
  4728. const path = expressionManager.getExpressionFile(definition);
  4729. (_a = tasks[index]) != null ? _a : tasks[index] = Live2DLoader.load({
  4730. url: path,
  4731. settings: expressionManager.settings,
  4732. type: "json",
  4733. target: expressionManager
  4734. }).then((data) => {
  4735. const tasks2 = _Live2DFactory.expressionTasksMap.get(expressionManager);
  4736. if (tasks2) {
  4737. delete tasks2[index];
  4738. }
  4739. const expression = expressionManager.createExpression(data, definition);
  4740. expressionManager.emit("expressionLoaded", index, expression);
  4741. return expression;
  4742. }).catch((e) => {
  4743. logger.warn(expressionManager.tag, `Failed to load expression: ${path}
  4744. `, e);
  4745. handleError(e);
  4746. });
  4747. return tasks[index];
  4748. } catch (e) {
  4749. logger.warn(expressionManager.tag, `Failed to load expression at [${index}]
  4750. `, e);
  4751. handleError(e);
  4752. }
  4753. return Promise.resolve(void 0);
  4754. }
  4755. static releaseTasks() {
  4756. if (this instanceof MotionManager) {
  4757. _Live2DFactory.motionTasksMap.delete(this);
  4758. } else {
  4759. _Live2DFactory.expressionTasksMap.delete(this);
  4760. }
  4761. }
  4762. };
  4763. var Live2DFactory = _Live2DFactory;
  4764. Live2DFactory.runtimes = [];
  4765. Live2DFactory.urlToJSON = urlToJSON;
  4766. Live2DFactory.jsonToSettings = jsonToSettings;
  4767. Live2DFactory.waitUntilReady = waitUntilReady;
  4768. Live2DFactory.setupOptionals = setupOptionals;
  4769. Live2DFactory.setupEssentials = setupEssentials;
  4770. Live2DFactory.createInternalModel = createInternalModel;
  4771. Live2DFactory.live2DModelMiddlewares = [
  4772. urlToJSON,
  4773. jsonToSettings,
  4774. waitUntilReady,
  4775. setupOptionals,
  4776. setupEssentials,
  4777. createInternalModel
  4778. ];
  4779. Live2DFactory.motionTasksMap = /* @__PURE__ */ new WeakMap();
  4780. Live2DFactory.expressionTasksMap = /* @__PURE__ */ new WeakMap();
  4781. MotionManager.prototype["_loadMotion"] = function(group, index) {
  4782. return Live2DFactory.loadMotion(this, group, index);
  4783. };
  4784. ExpressionManager.prototype["_loadExpression"] = function(index) {
  4785. return Live2DFactory.loadExpression(this, index);
  4786. };
  4787. var InteractionMixin = class {
  4788. constructor() {
  4789. this._autoInteract = false;
  4790. }
  4791. get autoInteract() {
  4792. return this._autoInteract;
  4793. }
  4794. set autoInteract(autoInteract) {
  4795. if (autoInteract !== this._autoInteract) {
  4796. if (autoInteract) {
  4797. this.on("pointertap", onTap, this);
  4798. } else {
  4799. this.off("pointertap", onTap, this);
  4800. }
  4801. this._autoInteract = autoInteract;
  4802. }
  4803. }
  4804. registerInteraction(manager) {
  4805. if (manager !== this.interactionManager) {
  4806. this.unregisterInteraction();
  4807. if (this._autoInteract && manager) {
  4808. this.interactionManager = manager;
  4809. manager.on("pointermove", onPointerMove, this);
  4810. }
  4811. }
  4812. }
  4813. unregisterInteraction() {
  4814. var _a;
  4815. if (this.interactionManager) {
  4816. (_a = this.interactionManager) == null ? void 0 : _a.off("pointermove", onPointerMove, this);
  4817. this.interactionManager = void 0;
  4818. }
  4819. }
  4820. };
  4821. function onTap(event) {
  4822. this.tap(event.data.global.x, event.data.global.y);
  4823. }
  4824. function onPointerMove(event) {
  4825. this.focus(event.data.global.x, event.data.global.y);
  4826. }
  4827. var Live2DTransform = class extends Transform {
  4828. };
  4829. var tempPoint = new Point();
  4830. var tempMatrix$1 = new Matrix();
  4831. var tickerRef;
  4832. var Live2DModel = class extends Container {
  4833. constructor(options) {
  4834. super();
  4835. this.tag = "Live2DModel(uninitialized)";
  4836. this.textures = [];
  4837. this.transform = new Live2DTransform();
  4838. this.anchor = new ObservablePoint(this.onAnchorChange, this, 0, 0);
  4839. this.glContextID = -1;
  4840. this.elapsedTime = performance.now();
  4841. this.deltaTime = 0;
  4842. this._autoUpdate = false;
  4843. this.once("modelLoaded", () => this.init(options));
  4844. }
  4845. static from(source, options) {
  4846. const model = new this(options);
  4847. return Live2DFactory.setupLive2DModel(model, source, options).then(() => model);
  4848. }
  4849. static fromSync(source, options) {
  4850. const model = new this(options);
  4851. Live2DFactory.setupLive2DModel(model, source, options).then(options == null ? void 0 : options.onLoad).catch(options == null ? void 0 : options.onError);
  4852. return model;
  4853. }
  4854. static registerTicker(tickerClass) {
  4855. tickerRef = tickerClass;
  4856. }
  4857. get autoUpdate() {
  4858. return this._autoUpdate;
  4859. }
  4860. set autoUpdate(autoUpdate) {
  4861. var _a;
  4862. tickerRef || (tickerRef = (_a = window.PIXI) == null ? void 0 : _a.Ticker);
  4863. if (autoUpdate) {
  4864. if (!this._destroyed) {
  4865. if (tickerRef) {
  4866. tickerRef.shared.add(this.onTickerUpdate, this);
  4867. this._autoUpdate = true;
  4868. } else {
  4869. logger.warn(this.tag, "No Ticker registered, please call Live2DModel.registerTicker(Ticker).");
  4870. }
  4871. }
  4872. } else {
  4873. tickerRef == null ? void 0 : tickerRef.shared.remove(this.onTickerUpdate, this);
  4874. this._autoUpdate = false;
  4875. }
  4876. }
  4877. init(options) {
  4878. this.tag = `Live2DModel(${this.internalModel.settings.name})`;
  4879. const _options = Object.assign({
  4880. autoUpdate: true,
  4881. autoInteract: true
  4882. }, options);
  4883. if (_options.autoInteract) {
  4884. this.interactive = true;
  4885. }
  4886. this.autoInteract = _options.autoInteract;
  4887. this.autoUpdate = _options.autoUpdate;
  4888. }
  4889. onAnchorChange() {
  4890. this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height);
  4891. }
  4892. motion(group, index, priority) {
  4893. return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority);
  4894. }
  4895. expression(id) {
  4896. if (this.internalModel.motionManager.expressionManager) {
  4897. return id === void 0 ? this.internalModel.motionManager.expressionManager.setRandomExpression() : this.internalModel.motionManager.expressionManager.setExpression(id);
  4898. }
  4899. return Promise.resolve(false);
  4900. }
  4901. focus(x, y, instant = false) {
  4902. tempPoint.x = x;
  4903. tempPoint.y = y;
  4904. this.toModelPosition(tempPoint, tempPoint, true);
  4905. let tx = tempPoint.x / this.internalModel.originalWidth * 2 - 1;
  4906. let ty = tempPoint.y / this.internalModel.originalHeight * 2 - 1;
  4907. let radian = Math.atan2(ty, tx);
  4908. this.internalModel.focusController.focus(Math.cos(radian), -Math.sin(radian), instant);
  4909. }
  4910. tap(x, y) {
  4911. const hitAreaNames = this.hitTest(x, y);
  4912. if (hitAreaNames.length) {
  4913. logger.log(this.tag, `Hit`, hitAreaNames);
  4914. this.emit("hit", hitAreaNames);
  4915. }
  4916. }
  4917. hitTest(x, y) {
  4918. tempPoint.x = x;
  4919. tempPoint.y = y;
  4920. this.toModelPosition(tempPoint, tempPoint);
  4921. return this.internalModel.hitTest(tempPoint.x, tempPoint.y);
  4922. }
  4923. toModelPosition(position, result = position.clone(), skipUpdate) {
  4924. if (!skipUpdate) {
  4925. this._recursivePostUpdateTransform();
  4926. if (!this.parent) {
  4927. this.parent = this._tempDisplayObjectParent;
  4928. this.displayObjectUpdateTransform();
  4929. this.parent = null;
  4930. } else {
  4931. this.displayObjectUpdateTransform();
  4932. }
  4933. }
  4934. this.transform.worldTransform.applyInverse(position, result);
  4935. this.internalModel.localTransform.applyInverse(result, result);
  4936. return result;
  4937. }
  4938. containsPoint(point) {
  4939. return this.getBounds(true).contains(point.x, point.y);
  4940. }
  4941. _calculateBounds() {
  4942. this._bounds.addFrame(this.transform, 0, 0, this.internalModel.width, this.internalModel.height);
  4943. }
  4944. onTickerUpdate() {
  4945. this.update(tickerRef.shared.deltaMS);
  4946. }
  4947. update(dt) {
  4948. this.deltaTime += dt;
  4949. this.elapsedTime += dt;
  4950. }
  4951. _render(renderer) {
  4952. this.registerInteraction(renderer.plugins.interaction);
  4953. renderer.batch.reset();
  4954. renderer.geometry.reset();
  4955. renderer.shader.reset();
  4956. renderer.state.reset();
  4957. let shouldUpdateTexture = false;
  4958. if (this.glContextID !== renderer.CONTEXT_UID) {
  4959. this.glContextID = renderer.CONTEXT_UID;
  4960. this.internalModel.updateWebGLContext(renderer.gl, this.glContextID);
  4961. shouldUpdateTexture = true;
  4962. }
  4963. for (let i = 0; i < this.textures.length; i++) {
  4964. const texture = this.textures[i];
  4965. if (!texture.valid) {
  4966. continue;
  4967. }
  4968. if (shouldUpdateTexture || !texture.baseTexture._glTextures[this.glContextID]) {
  4969. renderer.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL, this.internalModel.textureFlipY);
  4970. renderer.texture.bind(texture.baseTexture, 0);
  4971. }
  4972. this.internalModel.bindTexture(i, texture.baseTexture._glTextures[this.glContextID].texture);
  4973. texture.baseTexture.touched = renderer.textureGC.count;
  4974. }
  4975. const viewport = renderer.framebuffer.viewport;
  4976. this.internalModel.viewport = [viewport.x, viewport.y, viewport.width, viewport.height];
  4977. if (this.deltaTime) {
  4978. this.internalModel.update(this.deltaTime, this.elapsedTime);
  4979. this.deltaTime = 0;
  4980. }
  4981. const internalTransform = tempMatrix$1.copyFrom(renderer.globalUniforms.uniforms.projectionMatrix).append(this.worldTransform);
  4982. this.internalModel.updateTransform(internalTransform);
  4983. this.internalModel.draw(renderer.gl);
  4984. renderer.state.reset();
  4985. renderer.texture.reset();
  4986. }
  4987. destroy(options) {
  4988. this.emit("destroy");
  4989. this.autoUpdate = false;
  4990. this.unregisterInteraction();
  4991. if (options == null ? void 0 : options.texture) {
  4992. this.textures.forEach((texture) => texture.destroy(options.baseTexture));
  4993. }
  4994. this.internalModel.destroy();
  4995. super.destroy(options);
  4996. }
  4997. };
  4998. applyMixins(Live2DModel, [InteractionMixin]);
  4999. var _FileLoader = class {
  5000. static resolveURL(settingsURL, filePath) {
  5001. var _a;
  5002. const resolved = (_a = _FileLoader.filesMap[settingsURL]) == null ? void 0 : _a[filePath];
  5003. if (resolved === void 0) {
  5004. throw new Error("Cannot find this file from uploaded files: " + filePath);
  5005. }
  5006. return resolved;
  5007. }
  5008. static upload(files, settings) {
  5009. return __async(this, null, function* () {
  5010. const fileMap = {};
  5011. for (const definedFile of settings.getDefinedFiles()) {
  5012. const actualPath = decodeURI(url.resolve(settings.url, definedFile));
  5013. const actualFile = files.find((file) => file.webkitRelativePath === actualPath);
  5014. if (actualFile) {
  5015. fileMap[definedFile] = URL.createObjectURL(actualFile);
  5016. }
  5017. }
  5018. _FileLoader.filesMap[settings._objectURL] = fileMap;
  5019. });
  5020. }
  5021. static createSettings(files) {
  5022. return __async(this, null, function* () {
  5023. const settingsFile = files.find((file) => file.name.endsWith("model.json") || file.name.endsWith("model3.json"));
  5024. if (!settingsFile) {
  5025. throw new TypeError("Settings file not found");
  5026. }
  5027. const settingsText = yield _FileLoader.readText(settingsFile);
  5028. const settingsJSON = JSON.parse(settingsText);
  5029. settingsJSON.url = settingsFile.webkitRelativePath;
  5030. const runtime = Live2DFactory.findRuntime(settingsJSON);
  5031. if (!runtime) {
  5032. throw new Error("Unknown settings JSON");
  5033. }
  5034. const settings = runtime.createModelSettings(settingsJSON);
  5035. settings._objectURL = URL.createObjectURL(settingsFile);
  5036. return settings;
  5037. });
  5038. }
  5039. static readText(file) {
  5040. return __async(this, null, function* () {
  5041. return new Promise((resolve, reject) => {
  5042. const reader = new FileReader();
  5043. reader.onload = () => resolve(reader.result);
  5044. reader.onerror = reject;
  5045. reader.readAsText(file, "utf8");
  5046. });
  5047. });
  5048. }
  5049. };
  5050. var FileLoader = _FileLoader;
  5051. FileLoader.filesMap = {};
  5052. FileLoader.factory = (context, next) => __async(void 0, null, function* () {
  5053. if (Array.isArray(context.source) && context.source[0] instanceof File) {
  5054. const files = context.source;
  5055. let settings = files.settings;
  5056. if (!settings) {
  5057. settings = yield _FileLoader.createSettings(files);
  5058. } else if (!settings._objectURL) {
  5059. throw new Error('"_objectURL" must be specified in ModelSettings');
  5060. }
  5061. settings.validateFiles(files.map((file) => encodeURI(file.webkitRelativePath)));
  5062. yield _FileLoader.upload(files, settings);
  5063. settings.resolveURL = function(url2) {
  5064. return _FileLoader.resolveURL(this._objectURL, url2);
  5065. };
  5066. context.source = settings;
  5067. context.live2dModel.once("modelLoaded", (internalModel) => {
  5068. internalModel.once("destroy", function() {
  5069. const objectURL = this.settings._objectURL;
  5070. URL.revokeObjectURL(objectURL);
  5071. if (_FileLoader.filesMap[objectURL]) {
  5072. for (const resourceObjectURL of Object.values(_FileLoader.filesMap[objectURL])) {
  5073. URL.revokeObjectURL(resourceObjectURL);
  5074. }
  5075. }
  5076. delete _FileLoader.filesMap[objectURL];
  5077. });
  5078. });
  5079. }
  5080. return next();
  5081. });
  5082. Live2DFactory.live2DModelMiddlewares.unshift(FileLoader.factory);
  5083. var _ZipLoader = class {
  5084. static unzip(reader, settings) {
  5085. return __async(this, null, function* () {
  5086. const filePaths = yield _ZipLoader.getFilePaths(reader);
  5087. const requiredFilePaths = [];
  5088. for (const definedFile of settings.getDefinedFiles()) {
  5089. const actualPath = decodeURI(url.resolve(settings.url, definedFile));
  5090. if (filePaths.includes(actualPath)) {
  5091. requiredFilePaths.push(actualPath);
  5092. }
  5093. }
  5094. const files = yield _ZipLoader.getFiles(reader, requiredFilePaths);
  5095. for (let i = 0; i < files.length; i++) {
  5096. const path = requiredFilePaths[i];
  5097. const file = files[i];
  5098. Object.defineProperty(file, "webkitRelativePath", {
  5099. value: path
  5100. });
  5101. }
  5102. return files;
  5103. });
  5104. }
  5105. static createSettings(reader) {
  5106. return __async(this, null, function* () {
  5107. const filePaths = yield _ZipLoader.getFilePaths(reader);
  5108. const settingsFilePath = filePaths.find((path) => path.endsWith("model.json") || path.endsWith("model3.json"));
  5109. if (!settingsFilePath) {
  5110. throw new Error("Settings file not found");
  5111. }
  5112. const settingsText = yield _ZipLoader.readText(reader, settingsFilePath);
  5113. if (!settingsText) {
  5114. throw new Error("Empty settings file: " + settingsFilePath);
  5115. }
  5116. const settingsJSON = JSON.parse(settingsText);
  5117. settingsJSON.url = settingsFilePath;
  5118. const runtime = Live2DFactory.findRuntime(settingsJSON);
  5119. if (!runtime) {
  5120. throw new Error("Unknown settings JSON");
  5121. }
  5122. return runtime.createModelSettings(settingsJSON);
  5123. });
  5124. }
  5125. static zipReader(data, url2) {
  5126. return __async(this, null, function* () {
  5127. throw new Error("Not implemented");
  5128. });
  5129. }
  5130. static getFilePaths(reader) {
  5131. return __async(this, null, function* () {
  5132. throw new Error("Not implemented");
  5133. });
  5134. }
  5135. static getFiles(reader, paths) {
  5136. return __async(this, null, function* () {
  5137. throw new Error("Not implemented");
  5138. });
  5139. }
  5140. static readText(reader, path) {
  5141. return __async(this, null, function* () {
  5142. throw new Error("Not implemented");
  5143. });
  5144. }
  5145. static releaseReader(reader) {
  5146. }
  5147. };
  5148. var ZipLoader = _ZipLoader;
  5149. ZipLoader.ZIP_PROTOCOL = "zip://";
  5150. ZipLoader.uid = 0;
  5151. ZipLoader.factory = (context, next) => __async(void 0, null, function* () {
  5152. const source = context.source;
  5153. let sourceURL;
  5154. let zipBlob;
  5155. let settings;
  5156. if (typeof source === "string" && (source.endsWith(".zip") || source.startsWith(_ZipLoader.ZIP_PROTOCOL))) {
  5157. if (source.startsWith(_ZipLoader.ZIP_PROTOCOL)) {
  5158. sourceURL = source.slice(_ZipLoader.ZIP_PROTOCOL.length);
  5159. } else {
  5160. sourceURL = source;
  5161. }
  5162. zipBlob = yield Live2DLoader.load({
  5163. url: sourceURL,
  5164. type: "blob",
  5165. target: context.live2dModel
  5166. });
  5167. } else if (Array.isArray(source) && source.length === 1 && source[0] instanceof File && source[0].name.endsWith(".zip")) {
  5168. zipBlob = source[0];
  5169. sourceURL = URL.createObjectURL(zipBlob);
  5170. settings = source.settings;
  5171. }
  5172. if (zipBlob) {
  5173. if (!zipBlob.size) {
  5174. throw new Error("Empty zip file");
  5175. }
  5176. const reader = yield _ZipLoader.zipReader(zipBlob, sourceURL);
  5177. if (!settings) {
  5178. settings = yield _ZipLoader.createSettings(reader);
  5179. }
  5180. settings._objectURL = _ZipLoader.ZIP_PROTOCOL + _ZipLoader.uid + "/" + settings.url;
  5181. const files = yield _ZipLoader.unzip(reader, settings);
  5182. files.settings = settings;
  5183. context.source = files;
  5184. if (sourceURL.startsWith("blob:")) {
  5185. context.live2dModel.once("modelLoaded", (internalModel) => {
  5186. internalModel.once("destroy", function() {
  5187. URL.revokeObjectURL(sourceURL);
  5188. });
  5189. });
  5190. }
  5191. _ZipLoader.releaseReader(reader);
  5192. }
  5193. return next();
  5194. });
  5195. Live2DFactory.live2DModelMiddlewares.unshift(ZipLoader.factory);
  5196. if (!window.Live2DCubismCore) {
  5197. throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");
  5198. }
  5199. var Cubism4ExpressionManager = class extends ExpressionManager {
  5200. constructor(settings, options) {
  5201. var _a;
  5202. super(settings, options);
  5203. this.queueManager = new CubismMotionQueueManager();
  5204. this.definitions = (_a = settings.expressions) != null ? _a : [];
  5205. this.init();
  5206. }
  5207. isFinished() {
  5208. return this.queueManager.isFinished();
  5209. }
  5210. getExpressionIndex(name) {
  5211. return this.definitions.findIndex((def) => def.Name === name);
  5212. }
  5213. getExpressionFile(definition) {
  5214. return definition.File;
  5215. }
  5216. createExpression(data, definition) {
  5217. return CubismExpressionMotion.create(data);
  5218. }
  5219. _setExpression(motion) {
  5220. return this.queueManager.startMotion(motion, false, performance.now());
  5221. }
  5222. stopAllExpressions() {
  5223. this.queueManager.stopAllMotions();
  5224. }
  5225. updateParameters(model, now) {
  5226. return this.queueManager.doUpdateMotion(model, now);
  5227. }
  5228. };
  5229. var Cubism4ModelSettings = class _Cubism4ModelSettings extends ModelSettings {
  5230. constructor(json) {
  5231. super(json);
  5232. if (!_Cubism4ModelSettings.isValidJSON(json)) {
  5233. throw new TypeError("Invalid JSON.");
  5234. }
  5235. Object.assign(this, new CubismModelSettingsJson(json));
  5236. }
  5237. static isValidJSON(json) {
  5238. var _a;
  5239. return !!(json == null ? void 0 : json.FileReferences) && typeof json.FileReferences.Moc === "string" && ((_a = json.FileReferences.Textures) == null ? void 0 : _a.length) > 0 && json.FileReferences.Textures.every((item) => typeof item === "string");
  5240. }
  5241. replaceFiles(replace) {
  5242. super.replaceFiles(replace);
  5243. if (this.motions) {
  5244. for (const [group, motions] of Object.entries(this.motions)) {
  5245. for (let i = 0; i < motions.length; i++) {
  5246. motions[i].File = replace(motions[i].File, `motions.${group}[${i}].File`);
  5247. if (motions[i].Sound !== void 0) {
  5248. motions[i].Sound = replace(motions[i].Sound, `motions.${group}[${i}].Sound`);
  5249. }
  5250. }
  5251. }
  5252. }
  5253. if (this.expressions) {
  5254. for (let i = 0; i < this.expressions.length; i++) {
  5255. this.expressions[i].File = replace(this.expressions[i].File, `expressions[${i}].File`);
  5256. }
  5257. }
  5258. }
  5259. };
  5260. applyMixins(Cubism4ModelSettings, [CubismModelSettingsJson]);
  5261. var Cubism4MotionManager = class extends MotionManager {
  5262. constructor(settings, options) {
  5263. var _a;
  5264. super(settings, options);
  5265. this.groups = { idle: "Idle" };
  5266. this.motionDataType = "json";
  5267. this.queueManager = new CubismMotionQueueManager();
  5268. this.definitions = (_a = settings.motions) != null ? _a : {};
  5269. this.eyeBlinkIds = settings.getEyeBlinkParameters() || [];
  5270. this.lipSyncIds = settings.getLipSyncParameters() || [];
  5271. this.init(options);
  5272. }
  5273. init(options) {
  5274. super.init(options);
  5275. if (this.settings.expressions) {
  5276. this.expressionManager = new Cubism4ExpressionManager(this.settings, options);
  5277. }
  5278. this.queueManager.setEventCallback((caller, eventValue, customData) => {
  5279. this.emit("motion:" + eventValue);
  5280. });
  5281. }
  5282. isFinished() {
  5283. return this.queueManager.isFinished();
  5284. }
  5285. _startMotion(motion, onFinish) {
  5286. motion.setFinishedMotionHandler(onFinish);
  5287. this.queueManager.stopAllMotions();
  5288. return this.queueManager.startMotion(motion, false, performance.now());
  5289. }
  5290. _stopAllMotions() {
  5291. this.queueManager.stopAllMotions();
  5292. }
  5293. createMotion(data, group, definition) {
  5294. const motion = CubismMotion.create(data);
  5295. const json = new CubismMotionJson(data);
  5296. const defaultFadingDuration = (group === this.groups.idle ? config.idleMotionFadingDuration : config.motionFadingDuration) / 1e3;
  5297. if (json.getMotionFadeInTime() === void 0) {
  5298. motion.setFadeInTime(definition.FadeInTime > 0 ? definition.FadeInTime : defaultFadingDuration);
  5299. }
  5300. if (json.getMotionFadeOutTime() === void 0) {
  5301. motion.setFadeOutTime(definition.FadeOutTime > 0 ? definition.FadeOutTime : defaultFadingDuration);
  5302. }
  5303. motion.setEffectIds(this.eyeBlinkIds, this.lipSyncIds);
  5304. return motion;
  5305. }
  5306. getMotionFile(definition) {
  5307. return definition.File;
  5308. }
  5309. getMotionName(definition) {
  5310. return definition.File;
  5311. }
  5312. getSoundFile(definition) {
  5313. return definition.Sound;
  5314. }
  5315. updateParameters(model, now) {
  5316. return this.queueManager.doUpdateMotion(model, now);
  5317. }
  5318. destroy() {
  5319. super.destroy();
  5320. this.queueManager.release();
  5321. this.queueManager = void 0;
  5322. }
  5323. };
  5324. var tempMatrix = new CubismMatrix44();
  5325. var Cubism4InternalModel = class extends InternalModel {
  5326. constructor(coreModel, settings, options) {
  5327. super();
  5328. this.lipSync = true;
  5329. this.breath = CubismBreath.create();
  5330. this.renderer = new CubismRenderer_WebGL();
  5331. this.idParamAngleX = ParamAngleX;
  5332. this.idParamAngleY = ParamAngleY;
  5333. this.idParamAngleZ = ParamAngleZ;
  5334. this.idParamEyeBallX = ParamEyeBallX;
  5335. this.idParamEyeBallY = ParamEyeBallY;
  5336. this.idParamBodyAngleX = ParamBodyAngleX;
  5337. this.idParamBreath = ParamBreath;
  5338. this.pixelsPerUnit = 1;
  5339. this.centeringTransform = new Matrix();
  5340. this.coreModel = coreModel;
  5341. this.settings = settings;
  5342. this.motionManager = new Cubism4MotionManager(settings, options);
  5343. this.init();
  5344. }
  5345. init() {
  5346. var _a;
  5347. super.init();
  5348. if (((_a = this.settings.getEyeBlinkParameters()) == null ? void 0 : _a.length) > 0) {
  5349. this.eyeBlink = CubismEyeBlink.create(this.settings);
  5350. }
  5351. this.breath.setParameters([
  5352. new BreathParameterData(this.idParamAngleX, 0, 15, 6.5345, 0.5),
  5353. new BreathParameterData(this.idParamAngleY, 0, 8, 3.5345, 0.5),
  5354. new BreathParameterData(this.idParamAngleZ, 0, 10, 5.5345, 0.5),
  5355. new BreathParameterData(this.idParamBodyAngleX, 0, 4, 15.5345, 0.5),
  5356. new BreathParameterData(this.idParamBreath, 0, 0.5, 3.2345, 0.5)
  5357. ]);
  5358. this.renderer.initialize(this.coreModel);
  5359. this.renderer.setIsPremultipliedAlpha(true);
  5360. }
  5361. getSize() {
  5362. return [this.coreModel.getModel().canvasinfo.CanvasWidth, this.coreModel.getModel().canvasinfo.CanvasHeight];
  5363. }
  5364. getLayout() {
  5365. const layout = {};
  5366. if (this.settings.layout) {
  5367. for (const key of Object.keys(this.settings.layout)) {
  5368. const commonKey = key.charAt(0).toLowerCase() + key.slice(1);
  5369. layout[commonKey] = this.settings.layout[key];
  5370. }
  5371. }
  5372. return layout;
  5373. }
  5374. setupLayout() {
  5375. super.setupLayout();
  5376. this.pixelsPerUnit = this.coreModel.getModel().canvasinfo.PixelsPerUnit;
  5377. this.centeringTransform.scale(this.pixelsPerUnit, this.pixelsPerUnit).translate(this.originalWidth / 2, this.originalHeight / 2);
  5378. }
  5379. updateWebGLContext(gl, glContextID) {
  5380. this.renderer.firstDraw = true;
  5381. this.renderer._bufferData = {
  5382. vertex: null,
  5383. uv: null,
  5384. index: null
  5385. };
  5386. this.renderer.startUp(gl);
  5387. this.renderer._clippingManager._currentFrameNo = glContextID;
  5388. this.renderer._clippingManager._maskTexture = void 0;
  5389. CubismShader_WebGL.getInstance()._shaderSets = [];
  5390. }
  5391. bindTexture(index, texture) {
  5392. this.renderer.bindTexture(index, texture);
  5393. }
  5394. getHitAreaDefs() {
  5395. var _a, _b;
  5396. return (_b = (_a = this.settings.hitAreas) == null ? void 0 : _a.map((hitArea) => ({
  5397. id: hitArea.Id,
  5398. name: hitArea.Name,
  5399. index: this.coreModel.getDrawableIndex(hitArea.Id)
  5400. }))) != null ? _b : [];
  5401. }
  5402. getDrawableIDs() {
  5403. return this.coreModel.getDrawableIds();
  5404. }
  5405. getDrawableIndex(id) {
  5406. return this.coreModel.getDrawableIndex(id);
  5407. }
  5408. getDrawableVertices(drawIndex) {
  5409. if (typeof drawIndex === "string") {
  5410. drawIndex = this.coreModel.getDrawableIndex(drawIndex);
  5411. if (drawIndex === -1)
  5412. throw new TypeError("Unable to find drawable ID: " + drawIndex);
  5413. }
  5414. const arr = this.coreModel.getDrawableVertices(drawIndex).slice();
  5415. for (let i = 0; i < arr.length; i += 2) {
  5416. arr[i] = arr[i] * this.pixelsPerUnit + this.originalWidth / 2;
  5417. arr[i + 1] = -arr[i + 1] * this.pixelsPerUnit + this.originalHeight / 2;
  5418. }
  5419. return arr;
  5420. }
  5421. updateTransform(transform) {
  5422. this.drawingMatrix.copyFrom(this.centeringTransform).prepend(this.localTransform).prepend(transform);
  5423. }
  5424. update(dt, now) {
  5425. var _a, _b, _c, _d;
  5426. super.update(dt, now);
  5427. dt /= 1e3;
  5428. now /= 1e3;
  5429. const model = this.coreModel;
  5430. this.emit("beforeMotionUpdate");
  5431. const motionUpdated = this.motionManager.update(this.coreModel, now);
  5432. this.emit("afterMotionUpdate");
  5433. model.saveParameters();
  5434. (_a = this.motionManager.expressionManager) == null ? void 0 : _a.update(model, now);
  5435. if (!motionUpdated) {
  5436. (_b = this.eyeBlink) == null ? void 0 : _b.updateParameters(model, dt);
  5437. }
  5438. this.updateFocus();
  5439. this.updateNaturalMovements(dt * 1e3, now * 1e3);
  5440. (_c = this.physics) == null ? void 0 : _c.evaluate(model, dt);
  5441. (_d = this.pose) == null ? void 0 : _d.updateParameters(model, dt);
  5442. this.emit("beforeModelUpdate");
  5443. model.update();
  5444. model.loadParameters();
  5445. }
  5446. updateFocus() {
  5447. this.coreModel.addParameterValueById(this.idParamEyeBallX, this.focusController.x);
  5448. this.coreModel.addParameterValueById(this.idParamEyeBallY, this.focusController.y);
  5449. this.coreModel.addParameterValueById(this.idParamAngleX, this.focusController.x * 30);
  5450. this.coreModel.addParameterValueById(this.idParamAngleY, this.focusController.y * 30);
  5451. this.coreModel.addParameterValueById(this.idParamAngleZ, this.focusController.x * this.focusController.y * -30);
  5452. this.coreModel.addParameterValueById(this.idParamBodyAngleX, this.focusController.x * 10);
  5453. }
  5454. updateNaturalMovements(dt, now) {
  5455. var _a;
  5456. (_a = this.breath) == null ? void 0 : _a.updateParameters(this.coreModel, dt / 1e3);
  5457. }
  5458. draw(gl) {
  5459. const matrix = this.drawingMatrix;
  5460. const array = tempMatrix.getArray();
  5461. array[0] = matrix.a;
  5462. array[1] = matrix.b;
  5463. array[4] = -matrix.c;
  5464. array[5] = -matrix.d;
  5465. array[12] = matrix.tx;
  5466. array[13] = matrix.ty;
  5467. this.renderer.setMvpMatrix(tempMatrix);
  5468. this.renderer.setRenderState(gl.getParameter(gl.FRAMEBUFFER_BINDING), this.viewport);
  5469. this.renderer.drawModel();
  5470. }
  5471. destroy() {
  5472. super.destroy();
  5473. this.renderer.release();
  5474. this.coreModel.release();
  5475. this.renderer = void 0;
  5476. this.coreModel = void 0;
  5477. }
  5478. };
  5479. var startupPromise;
  5480. var startupRetries = 20;
  5481. function cubism4Ready() {
  5482. if (CubismFramework.isStarted()) {
  5483. return Promise.resolve();
  5484. }
  5485. startupPromise != null ? startupPromise : startupPromise = new Promise((resolve, reject) => {
  5486. function startUpWithRetry() {
  5487. try {
  5488. startUpCubism4();
  5489. resolve();
  5490. } catch (e) {
  5491. startupRetries--;
  5492. if (startupRetries < 0) {
  5493. const err = new Error("Failed to start up Cubism 4 framework.");
  5494. err.cause = e;
  5495. reject(err);
  5496. return;
  5497. }
  5498. logger.log("Cubism4", "Startup failed, retrying 10ms later...");
  5499. setTimeout(startUpWithRetry, 10);
  5500. }
  5501. }
  5502. startUpWithRetry();
  5503. });
  5504. return startupPromise;
  5505. }
  5506. function startUpCubism4(options) {
  5507. options = Object.assign({
  5508. logFunction: console.log,
  5509. loggingLevel: LogLevel.LogLevel_Verbose
  5510. }, options);
  5511. CubismFramework.startUp(options);
  5512. CubismFramework.initialize();
  5513. }
  5514. Live2DFactory.registerRuntime({
  5515. version: 4,
  5516. ready: cubism4Ready,
  5517. test(source) {
  5518. return source instanceof Cubism4ModelSettings || Cubism4ModelSettings.isValidJSON(source);
  5519. },
  5520. isValidMoc(modelData) {
  5521. if (modelData.byteLength < 4) {
  5522. return false;
  5523. }
  5524. const view = new Int8Array(modelData, 0, 4);
  5525. return String.fromCharCode(...view) === "MOC3";
  5526. },
  5527. createModelSettings(json) {
  5528. return new Cubism4ModelSettings(json);
  5529. },
  5530. createCoreModel(data) {
  5531. const moc = CubismMoc.create(data);
  5532. try {
  5533. const model = moc.createModel();
  5534. model.__moc = moc;
  5535. return model;
  5536. } catch (e) {
  5537. try {
  5538. moc.release();
  5539. } catch (ignored) {
  5540. }
  5541. throw e;
  5542. }
  5543. },
  5544. createInternalModel(coreModel, settings, options) {
  5545. const model = new Cubism4InternalModel(coreModel, settings, options);
  5546. const coreModelWithMoc = coreModel;
  5547. if (coreModelWithMoc.__moc) {
  5548. model.__moc = coreModelWithMoc.__moc;
  5549. delete coreModelWithMoc.__moc;
  5550. model.once("destroy", releaseMoc);
  5551. }
  5552. return model;
  5553. },
  5554. createPhysics(coreModel, data) {
  5555. return CubismPhysics.create(data);
  5556. },
  5557. createPose(coreModel, data) {
  5558. return CubismPose.create(data);
  5559. }
  5560. });
  5561. function releaseMoc() {
  5562. var _a;
  5563. (_a = this.__moc) == null ? void 0 : _a.release();
  5564. }
  5565. export {
  5566. ACubismMotion,
  5567. BreathParameterData,
  5568. CSM_ASSERT,
  5569. Constant,
  5570. Cubism4ExpressionManager,
  5571. Cubism4InternalModel,
  5572. Cubism4ModelSettings,
  5573. Cubism4MotionManager,
  5574. CubismBlendMode,
  5575. CubismBreath,
  5576. CubismClippingContext,
  5577. CubismClippingManager_WebGL,
  5578. CubismConfig,
  5579. CubismDebug,
  5580. CubismExpressionMotion,
  5581. CubismEyeBlink,
  5582. CubismFramework,
  5583. CubismLogDebug,
  5584. CubismLogError,
  5585. CubismLogInfo,
  5586. CubismLogVerbose,
  5587. CubismLogWarning,
  5588. CubismMath,
  5589. CubismMatrix44,
  5590. CubismMoc,
  5591. CubismModel,
  5592. CubismModelSettingsJson,
  5593. CubismModelUserData,
  5594. CubismModelUserDataJson,
  5595. CubismMotion,
  5596. CubismMotionCurve,
  5597. CubismMotionCurveTarget,
  5598. CubismMotionData,
  5599. CubismMotionEvent,
  5600. CubismMotionJson,
  5601. CubismMotionManager,
  5602. CubismMotionPoint,
  5603. CubismMotionQueueEntry,
  5604. CubismMotionQueueManager,
  5605. CubismMotionSegment,
  5606. CubismMotionSegmentType,
  5607. CubismPhysics,
  5608. CubismPhysicsInput,
  5609. CubismPhysicsJson,
  5610. CubismPhysicsOutput,
  5611. CubismPhysicsParticle,
  5612. CubismPhysicsRig,
  5613. CubismPhysicsSource,
  5614. CubismPhysicsSubRig,
  5615. CubismPhysicsTargetType,
  5616. CubismPose,
  5617. CubismRenderTextureResource,
  5618. CubismRenderer,
  5619. CubismRenderer_WebGL,
  5620. CubismShader_WebGL,
  5621. CubismTextureColor,
  5622. CubismVector2,
  5623. EvaluationOptionFlag,
  5624. ExpressionBlendType,
  5625. ExpressionManager,
  5626. EyeState,
  5627. FileLoader,
  5628. FocusController,
  5629. HitAreaBody,
  5630. HitAreaHead,
  5631. HitAreaPrefix,
  5632. InteractionMixin,
  5633. InternalModel,
  5634. InvalidMotionQueueEntryHandleValue,
  5635. LOGICAL_HEIGHT,
  5636. LOGICAL_WIDTH,
  5637. Live2DFactory,
  5638. Live2DLoader,
  5639. Live2DModel,
  5640. Live2DTransform,
  5641. LogLevel,
  5642. ModelSettings,
  5643. MotionManager,
  5644. MotionPreloadStrategy,
  5645. MotionPriority,
  5646. MotionState,
  5647. Options,
  5648. ParamAngleX,
  5649. ParamAngleY,
  5650. ParamAngleZ,
  5651. ParamArmLA,
  5652. ParamArmLB,
  5653. ParamArmRA,
  5654. ParamArmRB,
  5655. ParamBaseX,
  5656. ParamBaseY,
  5657. ParamBodyAngleX,
  5658. ParamBodyAngleY,
  5659. ParamBodyAngleZ,
  5660. ParamBreath,
  5661. ParamBrowLAngle,
  5662. ParamBrowLForm,
  5663. ParamBrowLX,
  5664. ParamBrowLY,
  5665. ParamBrowRAngle,
  5666. ParamBrowRForm,
  5667. ParamBrowRX,
  5668. ParamBrowRY,
  5669. ParamBustX,
  5670. ParamBustY,
  5671. ParamCheek,
  5672. ParamEyeBallForm,
  5673. ParamEyeBallX,
  5674. ParamEyeBallY,
  5675. ParamEyeLOpen,
  5676. ParamEyeLSmile,
  5677. ParamEyeROpen,
  5678. ParamEyeRSmile,
  5679. ParamHairBack,
  5680. ParamHairFluffy,
  5681. ParamHairFront,
  5682. ParamHairSide,
  5683. ParamHandL,
  5684. ParamHandR,
  5685. ParamMouthForm,
  5686. ParamMouthOpenY,
  5687. ParamNONE,
  5688. ParamShoulderY,
  5689. PartData,
  5690. PartsArmLPrefix,
  5691. PartsArmPrefix,
  5692. PartsArmRPrefix,
  5693. PartsIdCore,
  5694. PhysicsJsonEffectiveForces,
  5695. ShaderNames,
  5696. SoundManager,
  5697. VERSION,
  5698. XHRLoader,
  5699. ZipLoader,
  5700. applyMixins,
  5701. clamp,
  5702. config,
  5703. copyArray,
  5704. copyProperty,
  5705. csmRect,
  5706. cubism4Ready,
  5707. folderName,
  5708. fragmentShaderSrcMaskInvertedPremultipliedAlpha,
  5709. fragmentShaderSrcMaskPremultipliedAlpha,
  5710. fragmentShaderSrcPremultipliedAlpha,
  5711. fragmentShaderSrcsetupMask,
  5712. logger,
  5713. rand,
  5714. remove,
  5715. startUpCubism4,
  5716. vertexShaderSrc,
  5717. vertexShaderSrcMasked,
  5718. vertexShaderSrcSetupMask
  5719. };
  5720. //# sourceMappingURL=pixi-live2d-display_cubism4.js.map