engine-adapter.js 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863
  1. (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. "use strict";
  3. /****************************************************************************
  4. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  5. https://www.cocos.com/
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated engine source code (the "Software"), a limited,
  8. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  9. to use Cocos Creator solely to develop games on your target platforms. You shall
  10. not use Cocos Creator software for developing other software or tools that's
  11. used for developing games. You are not granted to publish, distribute,
  12. sublicense, and/or sell copies of Cocos Creator.
  13. The software or tools in this License Agreement are licensed, not sold.
  14. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. require('./jsb-assets-manager.js');
  24. require('./jsb-game.js');
  25. require('./jsb-gfx.js');
  26. require('./jsb-loader.js');
  27. require('./jsb-videoplayer.js');
  28. require('./jsb-webview.js');
  29. require('./jsb-editbox.js');
  30. require('./jsb-editor-support.js');
  31. require('./jsb-spine-skeleton.js');
  32. require('./jsb-dragonbones.js');
  33. if (cc.physics && cc.physics.PhysicsSystem.PHYSICS_PHYSX) {
  34. require('./jsb-physics.js');
  35. }
  36. },{"./jsb-assets-manager.js":2,"./jsb-dragonbones.js":4,"./jsb-editbox.js":5,"./jsb-editor-support.js":6,"./jsb-game.js":8,"./jsb-gfx.js":9,"./jsb-loader.js":10,"./jsb-physics.js":11,"./jsb-spine-skeleton.js":12,"./jsb-videoplayer.js":13,"./jsb-webview.js":14}],2:[function(require,module,exports){
  37. "use strict";
  38. /*
  39. * Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  40. *
  41. * Permission is hereby granted, free of charge, to any person obtaining a copy
  42. * of this software and associated documentation files (the "Software"), to deal
  43. * in the Software without restriction, including without limitation the rights
  44. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  45. * copies of the Software, and to permit persons to whom the Software is
  46. * furnished to do so, subject to the following conditions:
  47. *
  48. * The above copyright notice and this permission notice shall be included in
  49. * all copies or substantial portions of the Software.
  50. *
  51. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  52. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  53. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  54. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  55. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  56. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  57. * THE SOFTWARE.
  58. */
  59. if (jsb.AssetsManager) {
  60. jsb.AssetsManager.State = {
  61. UNINITED: 0,
  62. UNCHECKED: 1,
  63. PREDOWNLOAD_VERSION: 2,
  64. DOWNLOADING_VERSION: 3,
  65. VERSION_LOADED: 4,
  66. PREDOWNLOAD_MANIFEST: 5,
  67. DOWNLOADING_MANIFEST: 6,
  68. MANIFEST_LOADED: 7,
  69. NEED_UPDATE: 8,
  70. READY_TO_UPDATE: 9,
  71. UPDATING: 10,
  72. UNZIPPING: 11,
  73. UP_TO_DATE: 12,
  74. FAIL_TO_UPDATE: 13
  75. };
  76. jsb.Manifest.DownloadState = {
  77. UNSTARTED: 0,
  78. DOWNLOADING: 1,
  79. SUCCESSED: 2,
  80. UNMARKED: 3
  81. };
  82. jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0;
  83. jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1;
  84. jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2;
  85. jsb.EventAssetsManager.NEW_VERSION_FOUND = 3;
  86. jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4;
  87. jsb.EventAssetsManager.UPDATE_PROGRESSION = 5;
  88. jsb.EventAssetsManager.ASSET_UPDATED = 6;
  89. jsb.EventAssetsManager.ERROR_UPDATING = 7;
  90. jsb.EventAssetsManager.UPDATE_FINISHED = 8;
  91. jsb.EventAssetsManager.UPDATE_FAILED = 9;
  92. jsb.EventAssetsManager.ERROR_DECOMPRESS = 10;
  93. }
  94. },{}],3:[function(require,module,exports){
  95. "use strict";
  96. /****************************************************************************
  97. Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
  98. https://www.cocos.com/
  99. Permission is hereby granted, free of charge, to any person obtaining a copy
  100. of cache-manager software and associated engine source code (the "Software"), a limited,
  101. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  102. to use Cocos Creator solely to develop games on your target platforms. You shall
  103. not use Cocos Creator software for developing other software or tools that's
  104. used for developing games. You are not granted to publish, distribute,
  105. sublicense, and/or sell copies of Cocos Creator.
  106. The software or tools in cache-manager License Agreement are licensed, not sold.
  107. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  108. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  109. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  110. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  111. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  112. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  113. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  114. THE SOFTWARE.
  115. ****************************************************************************/
  116. const {
  117. getUserDataPath,
  118. readJsonSync,
  119. makeDirSync,
  120. writeFileSync,
  121. deleteFile,
  122. rmdirSync
  123. } = require('./jsb-fs-utils');
  124. var writeCacheFileList = null;
  125. var cleaning = false;
  126. const REGEX = /^\w+:\/\/.*/;
  127. var cacheManager = {
  128. cacheDir: 'gamecaches',
  129. cachedFileName: 'cacheList.json',
  130. deleteInterval: 500,
  131. writeFileInterval: 2000,
  132. cachedFiles: null,
  133. version: '1.1',
  134. getCache(url) {
  135. this.updateLastTime(url);
  136. return this.cachedFiles.has(url) ? `${this.cacheDir}/${this.cachedFiles.get(url).url}` : '';
  137. },
  138. getTemp(url) {
  139. return '';
  140. },
  141. init() {
  142. this.cacheDir = getUserDataPath() + '/' + this.cacheDir;
  143. var cacheFilePath = this.cacheDir + '/' + this.cachedFileName;
  144. var result = readJsonSync(cacheFilePath);
  145. if (result instanceof Error || !result.version || result.version !== this.version) {
  146. if (!(result instanceof Error)) rmdirSync(this.cacheDir, true);
  147. this.cachedFiles = new cc.AssetManager.Cache();
  148. makeDirSync(this.cacheDir, true);
  149. writeFileSync(cacheFilePath, JSON.stringify({
  150. files: this.cachedFiles._map,
  151. version: this.version
  152. }), 'utf8');
  153. } else {
  154. this.cachedFiles = new cc.AssetManager.Cache(result.files);
  155. }
  156. },
  157. updateLastTime(url) {
  158. if (this.cachedFiles.has(url)) {
  159. var cache = this.cachedFiles.get(url);
  160. cache.lastTime = Date.now();
  161. }
  162. },
  163. _write() {
  164. writeCacheFileList = null;
  165. writeFileSync(this.cacheDir + '/' + this.cachedFileName, JSON.stringify({
  166. files: this.cachedFiles._map,
  167. version: this.version
  168. }), 'utf8');
  169. },
  170. writeCacheFile() {
  171. if (!writeCacheFileList) {
  172. writeCacheFileList = setTimeout(this._write.bind(this), this.writeFileInterval);
  173. }
  174. },
  175. cacheFile(id, url, cacheBundleRoot) {
  176. this.cachedFiles.add(id, {
  177. bundle: cacheBundleRoot,
  178. url,
  179. lastTime: Date.now()
  180. });
  181. this.writeCacheFile();
  182. },
  183. clearCache() {
  184. rmdirSync(this.cacheDir, true);
  185. this.cachedFiles = new cc.AssetManager.Cache();
  186. makeDirSync(this.cacheDir, true);
  187. clearTimeout(writeCacheFileList);
  188. this._write();
  189. cc.assetManager.bundles.forEach(bundle => {
  190. if (REGEX.test(bundle.base)) this.makeBundleFolder(bundle.name);
  191. });
  192. },
  193. clearLRU() {
  194. if (cleaning) return;
  195. cleaning = true;
  196. var caches = [];
  197. var self = this;
  198. this.cachedFiles.forEach((val, key) => {
  199. if (val.bundle === 'internal') return;
  200. caches.push({
  201. originUrl: key,
  202. url: this.getCache(key),
  203. lastTime: val.lastTime
  204. });
  205. });
  206. caches.sort(function (a, b) {
  207. return a.lastTime - b.lastTime;
  208. });
  209. caches.length = Math.floor(caches.length / 3);
  210. if (caches.length === 0) return;
  211. for (var i = 0, l = caches.length; i < l; i++) {
  212. this.cachedFiles.remove(caches[i].originUrl);
  213. }
  214. clearTimeout(writeCacheFileList);
  215. this._write();
  216. function deferredDelete() {
  217. var item = caches.pop();
  218. deleteFile(item.url);
  219. if (caches.length > 0) {
  220. setTimeout(deferredDelete, self.deleteInterval);
  221. } else {
  222. cleaning = false;
  223. }
  224. }
  225. setTimeout(deferredDelete, self.deleteInterval);
  226. },
  227. removeCache(url) {
  228. if (this.cachedFiles.has(url)) {
  229. var path = this.getCache(url);
  230. this.cachedFiles.remove(url);
  231. clearTimeout(writeCacheFileList);
  232. this._write();
  233. deleteFile(path);
  234. }
  235. },
  236. makeBundleFolder(bundleName) {
  237. makeDirSync(this.cacheDir + '/' + bundleName, true);
  238. }
  239. };
  240. cc.assetManager.cacheManager = module.exports = cacheManager;
  241. },{"./jsb-fs-utils":7}],4:[function(require,module,exports){
  242. "use strict";
  243. /****************************************************************************
  244. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  245. http://www.cocos.com
  246. Permission is hereby granted, free of charge, to any person obtaining a copy
  247. of this software and associated engine source code (the "Software"), a limited,
  248. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  249. to use Cocos Creator solely to develop games on your target platforms. You shall
  250. not use Cocos Creator software for developing other software or tools that's
  251. used for developing games. You are not granted to publish, distribute,
  252. sublicense, and/or sell copies of Cocos Creator.
  253. The software or tools in this License Agreement are licensed, not sold.
  254. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  255. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  256. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  257. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  258. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  259. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  260. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  261. THE SOFTWARE.
  262. ****************************************************************************/
  263. const cacheManager = require('./jsb-cache-manager'); // @ts-expect-error jsb polyfills
  264. (function () {
  265. if (window.dragonBones === undefined || window.middleware === undefined) return;
  266. const ArmatureDisplayComponent = cc.internal.ArmatureDisplay;
  267. if (ArmatureDisplayComponent === undefined) return;
  268. const dragonBones = window.dragonBones;
  269. const middleware = window.middleware; // dragonbones global time scale.
  270. Object.defineProperty(dragonBones, 'timeScale', {
  271. get() {
  272. return this._timeScale;
  273. },
  274. set(value) {
  275. this._timeScale = value;
  276. const factory = this.CCFactory.getInstance();
  277. factory.setTimeScale(value);
  278. },
  279. configurable: true
  280. });
  281. middleware.generateGetSet(dragonBones);
  282. const _slotColor = cc.color(0, 0, 255, 255);
  283. const _boneColor = cc.color(255, 0, 0, 255);
  284. const _originColor = cc.color(0, 255, 0, 255); ////////////////////////////////////////////////////////////
  285. // override dragonBones library by native dragonBones
  286. ////////////////////////////////////////////////////////////
  287. //--------------------
  288. // adapt event name
  289. //--------------------
  290. dragonBones.EventObject.START = 'start';
  291. dragonBones.EventObject.LOOP_COMPLETE = 'loopComplete';
  292. dragonBones.EventObject.COMPLETE = 'complete';
  293. dragonBones.EventObject.FADE_IN = 'fadeIn';
  294. dragonBones.EventObject.FADE_IN_COMPLETE = 'fadeInComplete';
  295. dragonBones.EventObject.FADE_OUT = 'fadeOut';
  296. dragonBones.EventObject.FADE_OUT_COMPLETE = 'fadeOutComplete';
  297. dragonBones.EventObject.FRAME_EVENT = 'frameEvent';
  298. dragonBones.EventObject.SOUND_EVENT = 'soundEvent';
  299. dragonBones.DragonBones = {
  300. ANGLE_TO_RADIAN: Math.PI / 180,
  301. RADIAN_TO_ANGLE: 180 / Math.PI
  302. }; //-------------------
  303. // native factory
  304. //-------------------
  305. const factoryProto = dragonBones.CCFactory.prototype;
  306. factoryProto.createArmatureNode = function (comp, armatureName, node) {
  307. node = node || new cc.Node();
  308. let display = node.getComponent(ArmatureDisplayComponent);
  309. if (!display) {
  310. display = node.addComponent(ArmatureDisplayComponent);
  311. }
  312. node.name = armatureName;
  313. display._armatureName = armatureName;
  314. display._dragonAsset = comp.dragonAsset;
  315. display._dragonAtlasAsset = comp.dragonAtlasAsset;
  316. display._init();
  317. return display;
  318. };
  319. const _replaceSkin = factoryProto.replaceSkin;
  320. factoryProto.replaceSkin = function (armatrue, skinData, isOverride, exclude) {
  321. if (isOverride === undefined) isOverride = false;
  322. exclude = exclude || [];
  323. _replaceSkin.call(this, armatrue, skinData, isOverride, exclude);
  324. };
  325. const _changeSkin = factoryProto.changeSkin;
  326. factoryProto.changeSkin = function (armatrue, skinData, exclude) {
  327. _changeSkin.call(this, armatrue, skinData, exclude);
  328. };
  329. dragonBones.CCFactory.getInstance = function () {
  330. return dragonBones.CCFactory.getFactory();
  331. }; //-------------------
  332. // native animation state
  333. //-------------------
  334. const animationStateProto = dragonBones.AnimationState.prototype;
  335. const _isPlaying = animationStateProto.isPlaying;
  336. Object.defineProperty(animationStateProto, 'isPlaying', {
  337. get() {
  338. return _isPlaying.call(this);
  339. }
  340. }); //-------------------
  341. // native armature
  342. //-------------------
  343. const armatureProto = dragonBones.Armature.prototype;
  344. armatureProto.addEventListener = function (eventType, listener, target) {
  345. this.__persistentDisplay__ = this.getDisplay();
  346. this.__persistentDisplay__.on(eventType, listener, target);
  347. };
  348. armatureProto.removeEventListener = function (eventType, listener, target) {
  349. this.__persistentDisplay__ = this.getDisplay();
  350. this.__persistentDisplay__.off(eventType, listener, target);
  351. }; //--------------------------
  352. // native CCArmatureDisplay
  353. //--------------------------
  354. const nativeArmatureDisplayProto = dragonBones.CCArmatureDisplay.prototype;
  355. Object.defineProperty(nativeArmatureDisplayProto, 'node', {
  356. get() {
  357. return this;
  358. }
  359. });
  360. nativeArmatureDisplayProto.getRootNode = function () {
  361. const rootDisplay = this.getRootDisplay();
  362. return rootDisplay && rootDisplay._ccNode;
  363. };
  364. nativeArmatureDisplayProto.convertToWorldSpace = function (point) {
  365. let newPos = this.convertToRootSpace(point.x, point.y);
  366. newPos = cc.v3(newPos.x, newPos.y, 0);
  367. const ccNode = this.getRootNode();
  368. if (!ccNode) return newPos;
  369. const finalPos = ccNode._uiProps.uiTransformComp.convertToWorldSpaceAR(newPos);
  370. return finalPos;
  371. };
  372. nativeArmatureDisplayProto.initEvent = function () {
  373. if (this._eventTarget) {
  374. return;
  375. }
  376. this._eventTarget = new cc.EventTarget();
  377. this.setDBEventCallback(function (eventObject) {
  378. this._eventTarget.emit(eventObject.type, eventObject);
  379. });
  380. };
  381. nativeArmatureDisplayProto.on = function (type, listener, target) {
  382. this.initEvent();
  383. this._eventTarget.on(type, listener, target);
  384. this.addDBEventListener(type, listener);
  385. };
  386. nativeArmatureDisplayProto.off = function (type, listener, target) {
  387. this.initEvent();
  388. this._eventTarget.off(type, listener, target);
  389. this.removeDBEventListener(type, listener);
  390. };
  391. nativeArmatureDisplayProto.once = function (type, listener, target) {
  392. this.initEvent();
  393. this._eventTarget.once(type, listener, target);
  394. this.addDBEventListener(type, listener);
  395. }; ////////////////////////////////////////////////////////////
  396. // override DragonBonesAtlasAsset
  397. ////////////////////////////////////////////////////////////
  398. const dbAtlas = cc.internal.DragonBonesAtlasAsset.prototype;
  399. let _gTextureIdx = 1;
  400. const _textureKeyMap = {};
  401. const _textureMap = new WeakMap();
  402. const _textureIdx2Name = {};
  403. dbAtlas.removeRecordTexture = function (texture) {
  404. if (!texture) return;
  405. delete _textureIdx2Name[texture.image.url];
  406. const index = texture.__textureIndex__;
  407. if (index) {
  408. const texKey = _textureKeyMap[index];
  409. if (texKey && _textureMap.has(texKey)) {
  410. _textureMap.delete(texKey);
  411. delete _textureKeyMap[index];
  412. }
  413. }
  414. };
  415. dbAtlas.recordTexture = function () {
  416. if (this._texture && this._oldTexture !== this._texture) {
  417. this.removeRecordTexture(this._oldTexture);
  418. const texKey = _textureKeyMap[_gTextureIdx] = {
  419. key: _gTextureIdx
  420. };
  421. _textureMap.set(texKey, this._texture);
  422. this._oldTexture = this._texture;
  423. this._texture.__textureIndex__ = _gTextureIdx;
  424. _gTextureIdx++;
  425. }
  426. };
  427. dbAtlas.getTextureByIndex = function (textureIdx) {
  428. const texKey = _textureKeyMap[textureIdx];
  429. if (!texKey) return null;
  430. return _textureMap.get(texKey);
  431. };
  432. dbAtlas.updateTextureAtlasData = function (factory) {
  433. const url = this._texture.image.url;
  434. const preAtlasInfo = _textureIdx2Name[url];
  435. let index; // If the texture has store the atlas info before,then get native atlas object,and
  436. // update script texture map.
  437. if (preAtlasInfo) {
  438. index = preAtlasInfo.index;
  439. this._textureAtlasData = factory.getTextureAtlasDataByIndex(preAtlasInfo.name, index);
  440. const texKey = _textureKeyMap[preAtlasInfo.index];
  441. _textureMap.set(texKey, this._texture);
  442. this._texture.__textureIndex__ = index; // If script has store the atlas info,but native has no atlas object,then
  443. // still new native texture2d object,but no call recordTexture to increase
  444. // textureIndex.
  445. if (this._textureAtlasData) {
  446. return;
  447. }
  448. } else {
  449. this.recordTexture();
  450. }
  451. index = this._texture.__textureIndex__;
  452. this.jsbTexture = new middleware.Texture2D();
  453. this.jsbTexture.setRealTextureIndex(index);
  454. this.jsbTexture.setPixelsWide(this._texture.width);
  455. this.jsbTexture.setPixelsHigh(this._texture.height);
  456. this.jsbTexture.setRealTexture(this._texture);
  457. this._textureAtlasData = factory.parseTextureAtlasData(this.atlasJson, this.jsbTexture, this._uuid);
  458. _textureIdx2Name[url] = {
  459. name: this._textureAtlasData.name,
  460. index
  461. };
  462. };
  463. dbAtlas.init = function (factory) {
  464. this._factory = factory; // If create by manual, uuid is empty.
  465. if (!this._uuid) {
  466. const atlasJsonObj = JSON.parse(this.atlasJson);
  467. this._uuid = atlasJsonObj.name;
  468. }
  469. if (this._textureAtlasData) {
  470. factory.addTextureAtlasData(this._textureAtlasData, this._uuid);
  471. } else {
  472. this.updateTextureAtlasData(factory);
  473. }
  474. };
  475. dbAtlas._clear = function (dontRecordTexture) {
  476. if (this._factory) {
  477. this._factory.removeTextureAtlasData(this._uuid, true);
  478. this._factory.removeDragonBonesDataByUUID(this._uuid, true);
  479. }
  480. this._textureAtlasData = null;
  481. if (!dontRecordTexture) {
  482. this.recordTexture();
  483. }
  484. };
  485. dbAtlas.destroy = function () {
  486. this.removeRecordTexture(this._texture);
  487. this._clear(true);
  488. cc.Asset.prototype.destroy.call(this);
  489. }; ////////////////////////////////////////////////////////////
  490. // override DragonBonesAsset
  491. ////////////////////////////////////////////////////////////
  492. const dbAsset = cc.internal.DragonBonesAsset.prototype;
  493. dbAsset.init = function (factory, atlasUUID) {
  494. this._factory = factory; // If create by manual, uuid is empty.
  495. // Only support json format, if remote load dbbin, must set uuid by manual.
  496. if (!this._uuid && this.dragonBonesJson) {
  497. const rawData = JSON.parse(this.dragonBonesJson);
  498. this._uuid = rawData.name;
  499. }
  500. const armatureKey = `${this._uuid}#${atlasUUID}`;
  501. const dragonBonesData = this._factory.getDragonBonesData(armatureKey);
  502. if (dragonBonesData) return armatureKey;
  503. let filePath = null;
  504. if (this.dragonBonesJson) {
  505. filePath = this.dragonBonesJson;
  506. } else {
  507. filePath = cacheManager.getCache(this.nativeUrl) || this.nativeUrl;
  508. }
  509. this._factory.parseDragonBonesDataByPath(filePath, armatureKey);
  510. return armatureKey;
  511. };
  512. const armatureCacheMgr = dragonBones.ArmatureCacheMgr.getInstance();
  513. dragonBones.armatureCacheMgr = armatureCacheMgr;
  514. dbAsset._clear = function () {
  515. if (this._factory) {
  516. this._factory.removeDragonBonesDataByUUID(this._uuid, true);
  517. }
  518. armatureCacheMgr.removeArmatureCache(this._uuid);
  519. }; ////////////////////////////////////////////////////////////
  520. // override ArmatureDisplay
  521. ////////////////////////////////////////////////////////////
  522. const superProto = cc.internal.UIRenderer.prototype;
  523. const armatureDisplayProto = cc.internal.ArmatureDisplay.prototype;
  524. const AnimationCacheMode = cc.internal.ArmatureDisplay.AnimationCacheMode;
  525. const armatureSystem = cc.internal.ArmatureSystem;
  526. armatureDisplayProto.initFactory = function () {
  527. this._factory = dragonBones.CCFactory.getFactory();
  528. };
  529. Object.defineProperty(armatureDisplayProto, 'armatureName', {
  530. get() {
  531. return this._armatureName;
  532. },
  533. set(value) {
  534. this._armatureName = value;
  535. const animNames = this.getAnimationNames(this._armatureName);
  536. if (!this.animationName || animNames.indexOf(this.animationName) < 0) {
  537. this.animationName = '';
  538. }
  539. const oldArmature = this._armature;
  540. if (this._armature) {
  541. if (!this.isAnimationCached()) {
  542. this._factory.remove(this._armature);
  543. }
  544. this._armature = null;
  545. }
  546. this._nativeDisplay = null;
  547. this._refresh();
  548. if (oldArmature && oldArmature !== this._armature) {
  549. oldArmature.dispose();
  550. }
  551. if (this._armature && !this.isAnimationCached()) {
  552. this._factory.add(this._armature);
  553. }
  554. },
  555. visible: false
  556. });
  557. Object.defineProperty(armatureDisplayProto, 'premultipliedAlpha', {
  558. get() {
  559. if (this._premultipliedAlpha === undefined) {
  560. return false;
  561. }
  562. return this._premultipliedAlpha;
  563. },
  564. set(value) {
  565. this._premultipliedAlpha = value;
  566. if (this._nativeDisplay) {
  567. this._nativeDisplay.setOpacityModifyRGB(this._premultipliedAlpha);
  568. }
  569. }
  570. });
  571. const _initDebugDraw = armatureDisplayProto._initDebugDraw;
  572. armatureDisplayProto._initDebugDraw = function () {
  573. _initDebugDraw.call(this);
  574. if (this._armature && !this.isAnimationCached()) {
  575. this._nativeDisplay.setDebugBonesEnabled(this.debugBones);
  576. }
  577. };
  578. armatureDisplayProto._buildArmature = function () {
  579. if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) {
  580. return;
  581. }
  582. if (this._nativeDisplay) {
  583. this._nativeDisplay.dispose();
  584. this._nativeDisplay._comp = null;
  585. this._nativeDisplay = null;
  586. }
  587. const atlasUUID = this.dragonAtlasAsset._uuid;
  588. this._armatureKey = this.dragonAsset.init(this._factory, atlasUUID);
  589. if (this.isAnimationCached()) {
  590. const isShare = this._cacheMode === AnimationCacheMode.SHARED_CACHE;
  591. this._nativeDisplay = new dragonBones.CCArmatureCacheDisplay(this.armatureName, this._armatureKey, atlasUUID, isShare);
  592. this._armature = this._nativeDisplay.armature();
  593. } else {
  594. this._nativeDisplay = this._factory.buildArmatureDisplay(this.armatureName, this._armatureKey, '', atlasUUID);
  595. if (!this._nativeDisplay) {
  596. return;
  597. }
  598. this._nativeDisplay.setDebugBonesEnabled(this.debugBones);
  599. this._armature = this._nativeDisplay.armature();
  600. this._armature.animation.timeScale = this.timeScale;
  601. this._factory.add(this._armature);
  602. } // add all event into native display
  603. const callbackTable = this._eventTarget._callbackTable; // just use to adapt to native api
  604. const emptyHandle = function () {};
  605. for (const key in callbackTable) {
  606. const list = callbackTable[key];
  607. if (!list || !list.callbackInfos || !list.callbackInfos.length) continue;
  608. if (this.isAnimationCached()) {
  609. this._nativeDisplay.addDBEventListener(key);
  610. } else {
  611. this._nativeDisplay.addDBEventListener(key, emptyHandle);
  612. }
  613. }
  614. this._preCacheMode = this._cacheMode;
  615. this._nativeDisplay._ccNode = this.node;
  616. this._nativeDisplay._comp = this;
  617. this._nativeDisplay._eventTarget = this._eventTarget;
  618. this._sharedBufferOffset = this._nativeDisplay.getSharedBufferOffset();
  619. this._sharedBufferOffset[0] = 0;
  620. this._useAttach = false;
  621. this._nativeDisplay.setOpacityModifyRGB(this.premultipliedAlpha);
  622. const compColor = this.color;
  623. this._nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  624. this._nativeDisplay.setDBEventCallback(function (eventObject) {
  625. this._eventTarget.emit(eventObject.type, eventObject);
  626. });
  627. const materialTemplate = this.getMaterialTemplate();
  628. this._nativeDisplay.setMaterial(materialTemplate);
  629. this._nativeDisplay.setRenderEntity(this._renderEntity.nativeObj);
  630. this.attachUtil.init(this);
  631. if (this.animationName) {
  632. this.playAnimation(this.animationName, this.playTimes);
  633. }
  634. this.markForUpdateRenderData();
  635. };
  636. armatureDisplayProto._updateColor = function () {
  637. if (this._nativeDisplay) {
  638. const compColor = this.color;
  639. this._nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  640. }
  641. };
  642. armatureDisplayProto.playAnimation = function (animName, playTimes) {
  643. this.playTimes = playTimes === undefined ? -1 : playTimes;
  644. this.animationName = animName;
  645. if (this._nativeDisplay) {
  646. if (this.isAnimationCached()) {
  647. return this._nativeDisplay.playAnimation(animName, this.playTimes);
  648. } else if (this._armature) {
  649. return this._armature.animation.play(animName, this.playTimes);
  650. }
  651. }
  652. return null;
  653. };
  654. armatureDisplayProto.updateAnimationCache = function (animName) {
  655. if (!this.isAnimationCached()) return;
  656. if (this._nativeDisplay) {
  657. if (animName) {
  658. this._nativeDisplay.updateAnimationCache(animName);
  659. } else {
  660. this._nativeDisplay.updateAllAnimationCache();
  661. }
  662. }
  663. };
  664. armatureDisplayProto.invalidAnimationCache = function () {
  665. if (!this.isAnimationCached()) return;
  666. if (this._nativeDisplay) {
  667. this._nativeDisplay.updateAllAnimationCache();
  668. }
  669. };
  670. const _onEnable = superProto.onEnable;
  671. armatureDisplayProto.onEnable = function () {
  672. if (_onEnable) {
  673. _onEnable.call(this);
  674. }
  675. if (this._armature && !this.isAnimationCached()) {
  676. this._factory.add(this._armature);
  677. }
  678. this._flushAssembler();
  679. armatureSystem.getInstance().add(this);
  680. middleware.retain();
  681. };
  682. const _onDisable = superProto.onDisable;
  683. armatureDisplayProto.onDisable = function () {
  684. if (_onDisable) {
  685. _onDisable.call(this);
  686. }
  687. if (this._armature && !this.isAnimationCached()) {
  688. this._factory.remove(this._armature);
  689. }
  690. armatureSystem.getInstance().remove(this);
  691. middleware.release();
  692. };
  693. armatureDisplayProto.once = function (eventType, listener, target) {
  694. if (this._nativeDisplay) {
  695. if (this.isAnimationCached()) {
  696. this._nativeDisplay.addDBEventListener(eventType);
  697. } else {
  698. this._nativeDisplay.addDBEventListener(eventType, listener);
  699. }
  700. }
  701. this._eventTarget.once(eventType, listener, target);
  702. };
  703. armatureDisplayProto.addEventListener = function (eventType, listener, target) {
  704. if (this._nativeDisplay) {
  705. if (this.isAnimationCached()) {
  706. this._nativeDisplay.addDBEventListener(eventType);
  707. } else {
  708. this._nativeDisplay.addDBEventListener(eventType, listener);
  709. }
  710. }
  711. this._eventTarget.on(eventType, listener, target);
  712. };
  713. armatureDisplayProto.removeEventListener = function (eventType, listener, target) {
  714. if (this._nativeDisplay) {
  715. if (this.isAnimationCached()) {
  716. this._nativeDisplay.removeDBEventListener(eventType);
  717. } else {
  718. this._nativeDisplay.removeDBEventListener(eventType, listener);
  719. }
  720. }
  721. this._eventTarget.off(eventType, listener, target);
  722. };
  723. const _onDestroy = armatureDisplayProto.onDestroy;
  724. armatureDisplayProto.onDestroy = function () {
  725. _onDestroy.call(this);
  726. if (this._nativeDisplay) {
  727. this._nativeDisplay.dispose();
  728. this._nativeDisplay._comp = null;
  729. this._nativeDisplay = null;
  730. }
  731. };
  732. armatureDisplayProto.setAnimationCacheMode = function (cacheMode) {
  733. if (this._preCacheMode !== cacheMode) {
  734. this._cacheMode = cacheMode;
  735. this._buildArmature();
  736. if (this._armature && !this.isAnimationCached()) {
  737. this._factory.add(this._armature);
  738. }
  739. this._updateSocketBindings();
  740. this.markForUpdateRenderData();
  741. }
  742. };
  743. armatureDisplayProto.updateAnimation = function () {
  744. const nativeDisplay = this._nativeDisplay;
  745. if (!nativeDisplay) return;
  746. const node = this.node;
  747. if (!node) return;
  748. if (this.__preColor__ === undefined || !this.color.equals(this.__preColor__)) {
  749. const compColor = this.color;
  750. nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  751. this.__preColor__ = compColor;
  752. }
  753. const socketNodes = this.socketNodes;
  754. if (!this._useAttach && socketNodes.size > 0) {
  755. this._useAttach = true;
  756. nativeDisplay.setAttachEnabled(true);
  757. }
  758. this.markForUpdateRenderData();
  759. if (!this.isAnimationCached() && this._debugDraw && this.debugBones) {
  760. const nativeDisplay = this._nativeDisplay;
  761. this._debugData = this._debugData || nativeDisplay.getDebugData();
  762. if (!this._debugData) return;
  763. const graphics = this._debugDraw;
  764. graphics.clear();
  765. const debugData = this._debugData;
  766. let debugIdx = 0;
  767. graphics.lineWidth = 5;
  768. graphics.strokeColor = _boneColor;
  769. graphics.fillColor = _slotColor; // Root bone color is same as slot color.
  770. const debugBonesLen = debugData[debugIdx++];
  771. for (let i = 0; i < debugBonesLen; i += 4) {
  772. const bx = debugData[debugIdx++];
  773. const by = debugData[debugIdx++];
  774. const x = debugData[debugIdx++];
  775. const y = debugData[debugIdx++]; // Bone lengths.
  776. graphics.moveTo(bx, by);
  777. graphics.lineTo(x, y);
  778. graphics.stroke(); // Bone origins.
  779. graphics.circle(bx, by, Math.PI * 2);
  780. graphics.fill();
  781. if (i === 0) {
  782. graphics.fillColor = _originColor;
  783. }
  784. }
  785. }
  786. };
  787. const _tempAttachMat4 = cc.mat4();
  788. armatureDisplayProto._render = function () {
  789. const nativeDisplay = this._nativeDisplay;
  790. if (!nativeDisplay) return;
  791. const sharedBufferOffset = this._sharedBufferOffset;
  792. if (!sharedBufferOffset) return;
  793. const sockets = this.sockets;
  794. if (sockets.length > 0) {
  795. const attachInfoMgr = middleware.attachInfoMgr;
  796. const attachInfo = attachInfoMgr.attachInfo;
  797. const attachInfoOffset = sharedBufferOffset[0]; // reset attach info offset
  798. sharedBufferOffset[0] = 0;
  799. const socketNodes = this.socketNodes;
  800. for (let l = sockets.length - 1; l >= 0; l--) {
  801. const sock = sockets[l];
  802. const boneNode = sock.target;
  803. const boneIdx = sock.boneIndex;
  804. if (!boneNode) continue; // Node has been destroy
  805. if (!boneNode.isValid) {
  806. socketNodes.delete(sock.path);
  807. sockets.splice(l, 1);
  808. continue;
  809. }
  810. const tm = _tempAttachMat4;
  811. const matOffset = attachInfoOffset + boneIdx * 16;
  812. tm.m00 = attachInfo[matOffset];
  813. tm.m01 = attachInfo[matOffset + 1];
  814. tm.m04 = attachInfo[matOffset + 4];
  815. tm.m05 = attachInfo[matOffset + 5];
  816. tm.m12 = attachInfo[matOffset + 12];
  817. tm.m13 = attachInfo[matOffset + 13];
  818. boneNode.matrix = tm;
  819. }
  820. }
  821. };
  822. armatureDisplayProto._updateBatch = function () {
  823. if (this.nativeDisplay) {
  824. this.nativeDisplay.setBatchEnabled(this.enableBatch);
  825. this.markForUpdateRenderData();
  826. }
  827. }; //////////////////////////////////////////
  828. // assembler
  829. const assembler = cc.internal.DragonBonesAssembler; // eslint-disable-next-line no-unused-vars
  830. assembler.createData = function (comp) {};
  831. assembler.updateRenderData = function (comp) {
  832. comp._render();
  833. }; // eslint-disable-next-line no-unused-vars
  834. assembler.fillBuffers = function (comp, renderer) {};
  835. })();
  836. },{"./jsb-cache-manager":3}],5:[function(require,module,exports){
  837. "use strict";
  838. /****************************************************************************
  839. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  840. https://www.cocos.com/
  841. Permission is hereby granted, free of charge, to any person obtaining a copy
  842. of this software and associated engine source code (the "Software"), a limited,
  843. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  844. to use Cocos Creator solely to develop games on your target platforms. You shall
  845. not use Cocos Creator software for developing other software or tools that's
  846. used for developing games. You are not granted to publish, distribute,
  847. sublicense, and/or sell copies of Cocos Creator.
  848. The software or tools in this License Agreement are licensed, not sold.
  849. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  850. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  851. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  852. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  853. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  854. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  855. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  856. THE SOFTWARE.
  857. ****************************************************************************/
  858. (function () {
  859. if (!(cc && cc.internal && cc.internal.EditBox)) {
  860. return;
  861. }
  862. const EditBox = cc.internal.EditBox;
  863. const KeyboardReturnType = EditBox.KeyboardReturnType;
  864. const InputMode = EditBox.InputMode;
  865. const InputFlag = EditBox.InputFlag;
  866. const worldMat = cc.mat4();
  867. function getInputType(type) {
  868. switch (type) {
  869. case InputMode.EMAIL_ADDR:
  870. return 'email';
  871. case InputMode.NUMERIC:
  872. case InputMode.DECIMAL:
  873. return 'number';
  874. case InputMode.PHONE_NUMBER:
  875. return 'phone';
  876. case InputMode.URL:
  877. return 'url';
  878. case InputMode.SINGLE_LINE:
  879. case InputMode.ANY:
  880. default:
  881. return 'text';
  882. }
  883. }
  884. function getKeyboardReturnType(type) {
  885. switch (type) {
  886. case KeyboardReturnType.DEFAULT:
  887. case KeyboardReturnType.DONE:
  888. return 'done';
  889. case KeyboardReturnType.SEND:
  890. return 'send';
  891. case KeyboardReturnType.SEARCH:
  892. return 'search';
  893. case KeyboardReturnType.GO:
  894. return 'go';
  895. case KeyboardReturnType.NEXT:
  896. return 'next';
  897. }
  898. return 'done';
  899. }
  900. const BaseClass = EditBox._EditBoxImpl;
  901. class JsbEditBoxImpl extends BaseClass {
  902. init(delegate) {
  903. if (!delegate) {
  904. cc.error('EditBox init failed');
  905. return;
  906. }
  907. this._delegate = delegate;
  908. }
  909. beginEditing() {
  910. const self = this;
  911. const delegate = this._delegate;
  912. const multiline = delegate.inputMode === InputMode.ANY;
  913. const rect = this._getRect();
  914. this.setMaxLength(delegate.maxLength);
  915. let inputTypeString = getInputType(delegate.inputMode);
  916. if (delegate.inputFlag === InputFlag.PASSWORD) {
  917. inputTypeString = 'password';
  918. }
  919. function onConfirm(res) {
  920. delegate._editBoxEditingReturn();
  921. }
  922. function onInput(res) {
  923. if (res.value.length > self._maxLength) {
  924. res.value = res.value.slice(0, self._maxLength);
  925. }
  926. if (delegate.string !== res.value) {
  927. delegate._editBoxTextChanged(res.value);
  928. }
  929. }
  930. function onComplete(res) {
  931. self.endEditing();
  932. }
  933. jsb.inputBox.onInput(onInput);
  934. jsb.inputBox.onConfirm(onConfirm);
  935. jsb.inputBox.onComplete(onComplete);
  936. if (!cc.sys.isMobile) {
  937. delegate._hideLabels();
  938. }
  939. const editLabel = delegate.textLabel;
  940. jsb.inputBox.show({
  941. defaultValue: delegate.string,
  942. maxLength: self._maxLength,
  943. multiple: multiline,
  944. confirmHold: false,
  945. confirmType: getKeyboardReturnType(delegate.returnType),
  946. inputType: inputTypeString,
  947. originX: rect.x,
  948. originY: rect.y,
  949. width: rect.width,
  950. height: rect.height,
  951. isBold: editLabel.isBold,
  952. isItalic: editLabel.isItalic,
  953. isUnderline: editLabel.isUnderline,
  954. underlineColor: 0x00000000
  955. /* Black */
  956. ,
  957. fontSize:
  958. /**number */
  959. editLabel.fontSize,
  960. fontColor:
  961. /**number */
  962. editLabel.color.toRGBValue(),
  963. backColor: 0x00ffffff
  964. /*White*/
  965. ,
  966. backgroundColor: delegate.placeholderLabel.color.toRGBValue(),
  967. textAlignment:
  968. /*left = 0, center = 1, right = 2*/
  969. editLabel.horizontalAlign
  970. });
  971. this._editing = true;
  972. delegate._editBoxEditingDidBegan();
  973. }
  974. endEditing() {
  975. this._editing = false;
  976. if (!cc.sys.isMobile) {
  977. this._delegate._showLabels();
  978. }
  979. jsb.inputBox.offConfirm();
  980. jsb.inputBox.offInput();
  981. jsb.inputBox.offComplete();
  982. jsb.inputBox.hide();
  983. this._delegate._editBoxEditingDidEnded();
  984. }
  985. setMaxLength(maxLength) {
  986. if (!isNaN(maxLength)) {
  987. if (maxLength < 0) {
  988. //we can't set Number.MAX_VALUE to input's maxLength property
  989. //so we use a magic number here, it should works at most use cases.
  990. maxLength = 65535;
  991. }
  992. this._maxLength = maxLength;
  993. }
  994. }
  995. _getRect() {
  996. const node = this._delegate.node;
  997. let viewScaleX = cc.view._scaleX;
  998. let viewScaleY = cc.view._scaleY;
  999. const dpr = jsb.device.getDevicePixelRatio() || 1;
  1000. node.getWorldMatrix(worldMat);
  1001. const transform = node._uiProps.uiTransformComp;
  1002. const vec3 = cc.v3();
  1003. let width = 0;
  1004. let height = 0;
  1005. if (transform) {
  1006. const contentSize = transform.contentSize;
  1007. const anchorPoint = transform.anchorPoint;
  1008. width = contentSize.width;
  1009. height = contentSize.height;
  1010. vec3.x = -anchorPoint.x * width;
  1011. vec3.y = -anchorPoint.y * height;
  1012. }
  1013. cc.Mat4.translate(worldMat, worldMat, vec3);
  1014. viewScaleX /= dpr;
  1015. viewScaleY /= dpr;
  1016. const finalScaleX = worldMat.m00 * viewScaleX;
  1017. const finaleScaleY = worldMat.m05 * viewScaleY;
  1018. const viewportRect = cc.view._viewportRect;
  1019. const offsetX = viewportRect.x / dpr;
  1020. const offsetY = viewportRect.y / dpr;
  1021. return {
  1022. x: worldMat.m12 * viewScaleX + offsetX,
  1023. y: worldMat.m13 * viewScaleY + offsetY,
  1024. width: width * finalScaleX,
  1025. height: height * finaleScaleY
  1026. };
  1027. }
  1028. }
  1029. EditBox._EditBoxImpl = JsbEditBoxImpl;
  1030. })();
  1031. },{}],6:[function(require,module,exports){
  1032. "use strict";
  1033. /****************************************************************************
  1034. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  1035. http://www.cocos.com
  1036. Permission is hereby granted, free of charge, to any person obtaining a copy
  1037. of this software and associated engine source code (the "Software"), a limited,
  1038. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1039. to use Cocos Creator solely to develop games on your target platforms. You shall
  1040. not use Cocos Creator software for developing other software or tools that's
  1041. used for developing games. You are not granted to publish, distribute,
  1042. sublicense, and/or sell copies of Cocos Creator.
  1043. The software or tools in this License Agreement are licensed, not sold.
  1044. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1045. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1046. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1047. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1048. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1049. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1050. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1051. THE SOFTWARE.
  1052. ****************************************************************************/
  1053. // @ts-expect-error jsb polyfills
  1054. (function () {
  1055. if (!window.middleware) return;
  1056. const middleware = window.middleware;
  1057. const middlewareMgr = middleware.MiddlewareManager.getInstance();
  1058. let reference = 0;
  1059. const director = cc.director;
  1060. const game = cc.game;
  1061. middleware.reset = function () {
  1062. middleware.preRenderComponent = null;
  1063. middleware.preRenderBufferIndex = 0;
  1064. middleware.indicesStart = 0;
  1065. middleware.resetIndicesStart = false;
  1066. };
  1067. middleware.reset();
  1068. middleware.retain = function () {
  1069. reference++;
  1070. };
  1071. middleware.release = function () {
  1072. if (reference === 0) {
  1073. cc.warn('middleware reference error: reference count should be greater than 0');
  1074. return;
  1075. }
  1076. reference--;
  1077. };
  1078. director.on(cc.Director.EVENT_BEFORE_UPDATE, () => {
  1079. if (reference === 0) return;
  1080. middlewareMgr.update(game.deltaTime);
  1081. });
  1082. director.on(cc.Director.EVENT_BEFORE_DRAW, () => {
  1083. if (reference === 0) return;
  1084. middlewareMgr.render(game.deltaTime); // reset render order
  1085. middleware.reset(); //const batcher2D = director.root.batcher2D;
  1086. if (window.dragonBones) {
  1087. const armaSystem = cc.internal.ArmatureSystem.getInstance();
  1088. armaSystem.prepareRenderData();
  1089. }
  1090. if (window.spine) {
  1091. const skeletonSystem = cc.internal.SpineSkeletonSystem.getInstance();
  1092. skeletonSystem.prepareRenderData();
  1093. }
  1094. });
  1095. const attachInfoMgr = middlewareMgr.getAttachInfoMgr();
  1096. attachInfoMgr.attachInfo = attachInfoMgr.getSharedBuffer();
  1097. attachInfoMgr.setResizeCallback(function () {
  1098. this.attachInfo = this.getSharedBuffer();
  1099. });
  1100. middleware.attachInfoMgr = attachInfoMgr; // generate get set function
  1101. middleware.generateGetSet = function (moduleObj) {
  1102. for (const classKey in moduleObj) {
  1103. const classProto = moduleObj[classKey] && moduleObj[classKey].prototype;
  1104. if (!classProto) continue;
  1105. for (const getName in classProto) {
  1106. const getPos = getName.search(/^get/);
  1107. if (getPos === -1) continue;
  1108. let propName = getName.replace(/^get/, '');
  1109. const nameArr = propName.split('');
  1110. const lowerFirst = nameArr[0].toLowerCase();
  1111. const upperFirst = nameArr[0].toUpperCase();
  1112. nameArr.splice(0, 1);
  1113. const left = nameArr.join('');
  1114. propName = lowerFirst + left;
  1115. const setName = `set${upperFirst}${left}`; // eslint-disable-next-line no-prototype-builtins
  1116. if (classProto.hasOwnProperty(propName)) continue;
  1117. const setFunc = classProto[setName];
  1118. const hasSetFunc = typeof setFunc === 'function';
  1119. if (hasSetFunc) {
  1120. Object.defineProperty(classProto, propName, {
  1121. get() {
  1122. return this[getName]();
  1123. },
  1124. set(val) {
  1125. this[setName](val);
  1126. },
  1127. configurable: true
  1128. });
  1129. } else {
  1130. Object.defineProperty(classProto, propName, {
  1131. get() {
  1132. return this[getName]();
  1133. },
  1134. configurable: true
  1135. });
  1136. }
  1137. }
  1138. }
  1139. };
  1140. })();
  1141. },{}],7:[function(require,module,exports){
  1142. "use strict";
  1143. /****************************************************************************
  1144. Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
  1145. https://www.cocos.com/
  1146. Permission is hereby granted, free of charge, to any person obtaining a copy
  1147. of fsUtils software and associated engine source code (the "Software"), a limited,
  1148. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1149. to use Cocos Creator solely to develop games on your target platforms. You shall
  1150. not use Cocos Creator software for developing other software or tools that's
  1151. used for developing games. You are not granted to publish, distribute,
  1152. sublicense, and/or sell copies of Cocos Creator.
  1153. The software or tools in fsUtils License Agreement are licensed, not sold.
  1154. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1155. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1156. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1157. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1158. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1159. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1160. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1161. THE SOFTWARE.
  1162. ****************************************************************************/
  1163. const fs = jsb.fileUtils;
  1164. let jsb_downloader = null;
  1165. const downloading = new cc.AssetManager.Cache();
  1166. let tempDir = '';
  1167. jsb.Downloader.prototype._ctor = function () {
  1168. this.__nativeRefs = {};
  1169. };
  1170. var fsUtils = {
  1171. fs,
  1172. initJsbDownloader(jsbDownloaderMaxTasks, jsbDownloaderTimeout) {
  1173. jsb_downloader = new jsb.Downloader({
  1174. countOfMaxProcessingTasks: jsbDownloaderMaxTasks || 32,
  1175. timeoutInSeconds: jsbDownloaderTimeout || 30,
  1176. tempFileNameSuffix: '.tmp'
  1177. });
  1178. tempDir = `${fsUtils.getUserDataPath()}/temp`;
  1179. !fs.isDirectoryExist(tempDir) && fs.createDirectory(tempDir);
  1180. jsb_downloader.onSuccess = task => {
  1181. if (!downloading.has(task.requestURL)) return;
  1182. const {
  1183. onComplete
  1184. } = downloading.remove(task.requestURL);
  1185. onComplete && onComplete(null, task.storagePath);
  1186. };
  1187. jsb_downloader.onError = (task, errorCode, errorCodeInternal, errorStr) => {
  1188. if (!downloading.has(task.requestURL)) return;
  1189. const {
  1190. onComplete
  1191. } = downloading.remove(task.requestURL);
  1192. cc.error(`Download file failed: path: ${task.requestURL} message: ${errorStr}, ${errorCode}`);
  1193. onComplete(new Error(errorStr), null);
  1194. };
  1195. jsb_downloader.onProgress = (task, bytesReceived, totalBytesReceived, totalBytesExpected) => {
  1196. if (!downloading.has(task.requestURL)) return;
  1197. const {
  1198. onProgress
  1199. } = downloading.get(task.requestURL);
  1200. onProgress && onProgress(totalBytesReceived, totalBytesExpected);
  1201. };
  1202. },
  1203. getUserDataPath() {
  1204. return fs.getWritablePath().replace(/[\/\\]*$/, '');
  1205. },
  1206. checkFsValid() {
  1207. if (!fs) {
  1208. cc.warn('can not get the file system!');
  1209. return false;
  1210. }
  1211. return true;
  1212. },
  1213. deleteFile(filePath, onComplete) {
  1214. const result = fs.removeFile(filePath);
  1215. if (result === true) {
  1216. onComplete && onComplete(null);
  1217. } else {
  1218. cc.warn(`Delete file failed: path: ${filePath}`);
  1219. onComplete && onComplete(new Error('delete file failed'));
  1220. }
  1221. },
  1222. downloadFile(remoteUrl, filePath, header, onProgress, onComplete) {
  1223. downloading.add(remoteUrl, {
  1224. onProgress,
  1225. onComplete
  1226. });
  1227. let storagePath = filePath;
  1228. if (!storagePath) storagePath = `${tempDir}/${performance.now()}${cc.path.extname(remoteUrl)}`;
  1229. jsb_downloader.createDownloadTask(remoteUrl, storagePath, header);
  1230. },
  1231. saveFile(srcPath, destPath, onComplete) {
  1232. let err = null;
  1233. const result = fs.writeDataToFile(fs.getDataFromFile(srcPath), destPath);
  1234. fs.removeFile(srcPath);
  1235. if (!result) {
  1236. err = new Error(`Save file failed: path: ${srcPath}`);
  1237. cc.warn(err.message);
  1238. }
  1239. onComplete && onComplete(err);
  1240. },
  1241. copyFile(srcPath, destPath, onComplete) {
  1242. let err = null;
  1243. const result = fs.writeDataToFile(fs.getDataFromFile(srcPath), destPath);
  1244. if (!result) {
  1245. err = new Error(`Copy file failed: path: ${srcPath}`);
  1246. cc.warn(err.message);
  1247. }
  1248. onComplete && onComplete(err);
  1249. },
  1250. writeFile(path, data, encoding, onComplete) {
  1251. let result = null;
  1252. let err = null;
  1253. if (encoding === 'utf-8' || encoding === 'utf8') {
  1254. result = fs.writeStringToFile(data, path);
  1255. } else {
  1256. result = fs.writeDataToFile(data, path);
  1257. }
  1258. if (!result) {
  1259. err = new Error(`Write file failed: path: ${path}`);
  1260. cc.warn(err.message);
  1261. }
  1262. onComplete && onComplete(err);
  1263. },
  1264. writeFileSync(path, data, encoding) {
  1265. let result = null;
  1266. if (encoding === 'utf-8' || encoding === 'utf8') {
  1267. result = fs.writeStringToFile(data, path);
  1268. } else {
  1269. result = fs.writeDataToFile(data, path);
  1270. }
  1271. if (!result) {
  1272. cc.warn(`Write file failed: path: ${path}`);
  1273. return new Error(`Write file failed: path: ${path}`);
  1274. }
  1275. },
  1276. readFile(filePath, encoding, onComplete) {
  1277. let content = null;
  1278. let err = null;
  1279. if (encoding === 'utf-8' || encoding === 'utf8') {
  1280. content = fs.getStringFromFile(filePath);
  1281. } else {
  1282. content = fs.getDataFromFile(filePath);
  1283. }
  1284. if (!content) {
  1285. err = new Error(`Read file failed: path: ${filePath}`);
  1286. cc.warn(err.message);
  1287. }
  1288. onComplete && onComplete(err, content);
  1289. },
  1290. readDir(filePath, onComplete) {
  1291. let files = null;
  1292. let err = null;
  1293. try {
  1294. files = fs.listFiles(filePath);
  1295. } catch (e) {
  1296. cc.warn(`Read dir failed: path: ${filePath} message: ${e.message}`);
  1297. err = new Error(e.message);
  1298. }
  1299. onComplete && onComplete(err, files);
  1300. },
  1301. readText(filePath, onComplete) {
  1302. fsUtils.readFile(filePath, 'utf8', onComplete);
  1303. },
  1304. readArrayBuffer(filePath, onComplete) {
  1305. fsUtils.readFile(filePath, '', onComplete);
  1306. },
  1307. readJson(filePath, onComplete) {
  1308. fsUtils.readFile(filePath, 'utf8', (err, text) => {
  1309. let out = null;
  1310. if (!err) {
  1311. try {
  1312. out = JSON.parse(text);
  1313. } catch (e) {
  1314. cc.warn(`Read json failed: path: ${filePath} message: ${e.message}`);
  1315. err = new Error(e.message);
  1316. }
  1317. }
  1318. onComplete && onComplete(err, out);
  1319. });
  1320. },
  1321. readJsonSync(path) {
  1322. try {
  1323. const str = fs.getStringFromFile(path);
  1324. return JSON.parse(str);
  1325. } catch (e) {
  1326. cc.warn(`Read json failed: path: ${path} message: ${e.message}`);
  1327. return new Error(e.message);
  1328. }
  1329. },
  1330. makeDirSync(path, recursive) {
  1331. const result = fs.createDirectory(path);
  1332. if (!result) {
  1333. cc.warn(`Make directory failed: path: ${path}`);
  1334. return new Error(`Make directory failed: path: ${path}`);
  1335. }
  1336. },
  1337. rmdirSync(dirPath, recursive) {
  1338. const result = fs.removeDirectory(dirPath);
  1339. if (!result) {
  1340. cc.warn(`rm directory failed: path: ${dirPath}`);
  1341. return new Error(`rm directory failed: path: ${dirPath}`);
  1342. }
  1343. },
  1344. exists(filePath, onComplete) {
  1345. const result = fs.isFileExist(filePath);
  1346. onComplete && onComplete(result);
  1347. },
  1348. loadSubpackage(name, onProgress, onComplete) {
  1349. throw new Error('not implement');
  1350. }
  1351. };
  1352. window.fsUtils = module.exports = fsUtils;
  1353. },{}],8:[function(require,module,exports){
  1354. "use strict";
  1355. /****************************************************************************
  1356. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  1357. https://www.cocos.com/
  1358. Permission is hereby granted, free of charge, to any person obtaining a copy
  1359. of this software and associated engine source code (the "Software"), a limited,
  1360. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1361. to use Cocos Creator solely to develop games on your target platforms. You shall
  1362. not use Cocos Creator software for developing other software or tools that's
  1363. used for developing games. You are not granted to publish, distribute,
  1364. sublicense, and/or sell copies of Cocos Creator.
  1365. The software or tools in this License Agreement are licensed, not sold.
  1366. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1367. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1368. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1369. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1370. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1371. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1372. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1373. THE SOFTWARE.
  1374. ****************************************************************************/
  1375. cc.game.restart = function () {
  1376. // Need to clear scene, or native object destructor won't be invoke.
  1377. cc.director.getScene().destroy();
  1378. cc.Object._deferredDestroy();
  1379. __restartVM();
  1380. };
  1381. jsb.onError(function (location, message, stack) {
  1382. console.error(location, message, stack);
  1383. });
  1384. jsb.onMemoryWarning = function () {
  1385. cc.game.emit(cc.Game.EVENT_LOW_MEMORY);
  1386. };
  1387. },{}],9:[function(require,module,exports){
  1388. "use strict";
  1389. /****************************************************************************
  1390. Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
  1391. https://www.cocos.com/
  1392. Permission is hereby granted, free of charge, to any person obtaining a copy
  1393. of this software and associated engine source code (the "Software"), a limited,
  1394. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1395. to use Cocos Creator solely to develop games on your target platforms. You shall
  1396. not use Cocos Creator software for developing other software or tools that's
  1397. used for developing games. You are not granted to publish, distribute,
  1398. sublicense, and/or sell copies of Cocos Creator.
  1399. The software or tools in this License Agreement are licensed, not sold.
  1400. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1401. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1402. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1403. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1404. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1405. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1406. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1407. THE SOFTWARE.
  1408. ****************************************************************************/
  1409. /* global gfx */
  1410. const deviceProto = gfx.Device.prototype;
  1411. const swapchainProto = gfx.Swapchain.prototype;
  1412. const bufferProto = gfx.Buffer.prototype;
  1413. const textureProto = gfx.Texture.prototype;
  1414. const descriptorSetProto = gfx.DescriptorSet.prototype; ///////////////////////////// handle different paradigms /////////////////////////////
  1415. const oldCopyTexImagesToTextureFunc = deviceProto.copyTexImagesToTexture;
  1416. deviceProto.copyTexImagesToTexture = function (texImages, texture, regions) {
  1417. const images = [];
  1418. if (texImages) {
  1419. for (let i = 0; i < texImages.length; ++i) {
  1420. const texImage = texImages[i];
  1421. if (texImage instanceof HTMLCanvasElement) {
  1422. // Refer to HTMLCanvasElement and ImageData implementation
  1423. images.push(texImage._data.data);
  1424. } else if (texImage instanceof HTMLImageElement) {
  1425. // Refer to HTMLImageElement implementation
  1426. images.push(texImage._data);
  1427. } else {
  1428. console.log('copyTexImagesToTexture: Convert texImages to data buffers failed');
  1429. return;
  1430. }
  1431. }
  1432. }
  1433. oldCopyTexImagesToTextureFunc.call(this, images, texture, regions);
  1434. };
  1435. const oldDeviceCreateSwapchainFunc = deviceProto.createSwapchain;
  1436. deviceProto.createSwapchain = function (info) {
  1437. info.windowHandle = window.windowHandler;
  1438. return oldDeviceCreateSwapchainFunc.call(this, info);
  1439. };
  1440. const oldSwapchainInitializeFunc = swapchainProto.initialize;
  1441. swapchainProto.initialize = function (info) {
  1442. info.windowHandle = window.windowHandler;
  1443. oldSwapchainInitializeFunc.call(this, info);
  1444. };
  1445. const oldUpdate = bufferProto.update;
  1446. bufferProto.update = function (buffer, size) {
  1447. if (buffer.byteLength === 0) return;
  1448. let buffSize;
  1449. if (this.cachedUsage & 0x40) {
  1450. // BufferUsageBit.INDIRECT
  1451. // It is a IIndirectBuffer object.
  1452. const {
  1453. drawInfos
  1454. } = buffer;
  1455. buffer = new Uint32Array(drawInfos.length * 7);
  1456. let baseIndex = 0;
  1457. let drawInfo;
  1458. for (let i = 0; i < drawInfos.length; ++i) {
  1459. baseIndex = i * 7;
  1460. drawInfo = drawInfos[i];
  1461. buffer[baseIndex] = drawInfo.vertexCount;
  1462. buffer[baseIndex + 1] = drawInfo.firstVertex;
  1463. buffer[baseIndex + 2] = drawInfo.indexCount;
  1464. buffer[baseIndex + 3] = drawInfo.firstIndex;
  1465. buffer[baseIndex + 4] = drawInfo.vertexOffset;
  1466. buffer[baseIndex + 5] = drawInfo.instanceCount;
  1467. buffer[baseIndex + 6] = drawInfo.firstInstance;
  1468. }
  1469. buffSize = buffer.byteLength;
  1470. } else if (size !== undefined) {
  1471. buffSize = size;
  1472. } else {
  1473. buffSize = buffer.byteLength;
  1474. }
  1475. oldUpdate.call(this, buffer, buffSize);
  1476. };
  1477. const oldDeviceCreateBufferFun = deviceProto.createBuffer;
  1478. deviceProto.createBuffer = function (info) {
  1479. let buffer;
  1480. if (info.buffer) {
  1481. buffer = oldDeviceCreateBufferFun.call(this, info, true);
  1482. } else {
  1483. buffer = oldDeviceCreateBufferFun.call(this, info, false);
  1484. }
  1485. buffer.cachedUsage = info.usage;
  1486. return buffer;
  1487. };
  1488. const oldBufferInitializeFunc = bufferProto.initialize;
  1489. bufferProto.initialize = function (info) {
  1490. if (info.buffer) {
  1491. oldBufferInitializeFunc.call(this, info, true);
  1492. } else {
  1493. oldBufferInitializeFunc.call(this, info, false);
  1494. }
  1495. };
  1496. const oldDeviceCreateTextureFun = deviceProto.createTexture;
  1497. deviceProto.createTexture = function (info) {
  1498. if (info.texture) {
  1499. return oldDeviceCreateTextureFun.call(this, info, true);
  1500. }
  1501. return oldDeviceCreateTextureFun.call(this, info, false);
  1502. };
  1503. const oldTextureInitializeFunc = textureProto.initialize;
  1504. textureProto.initialize = function (info) {
  1505. if (info.texture) {
  1506. oldTextureInitializeFunc.call(this, info, true);
  1507. } else {
  1508. oldTextureInitializeFunc.call(this, info, false);
  1509. }
  1510. }; ///////////////////////////// optimizations /////////////////////////////
  1511. // Cache dirty to avoid invoking gfx.DescriptorSet.update().
  1512. descriptorSetProto.bindBuffer = function (binding, buffer, index) {
  1513. this.dirtyJSB = descriptorSetProto.bindBufferJSB.call(this, binding, buffer, index || 0);
  1514. };
  1515. descriptorSetProto.bindSampler = function (binding, sampler, index) {
  1516. this.dirtyJSB = descriptorSetProto.bindSamplerJSB.call(this, binding, sampler, index || 0);
  1517. };
  1518. descriptorSetProto.bindTexture = function (bindding, texture, index) {
  1519. this.dirtyJSB = descriptorSetProto.bindTextureJSB.call(this, bindding, texture, index || 0);
  1520. };
  1521. const oldDSUpdate = descriptorSetProto.update;
  1522. descriptorSetProto.update = function () {
  1523. if (!this.dirtyJSB) return;
  1524. oldDSUpdate.call(this);
  1525. this.dirtyJSB = false;
  1526. };
  1527. Object.defineProperty(deviceProto, 'uboOffsetAlignment', {
  1528. get() {
  1529. if (this.cachedUboOffsetAlignment === undefined) {
  1530. this.cachedUboOffsetAlignment = this.getUboOffsetAlignment();
  1531. }
  1532. return this.cachedUboOffsetAlignment;
  1533. }
  1534. });
  1535. },{}],10:[function(require,module,exports){
  1536. /****************************************************************************
  1537. Copyright (c) 2013-2016 Chukong Technologies Inc.
  1538. Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
  1539. https://www.cocos.com/
  1540. Permission is hereby granted, free of charge, to any person obtaining a copy
  1541. of this software and associated engine source code (the "Software"), a limited,
  1542. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1543. to use Cocos Creator solely to develop games on your target platforms. You shall
  1544. not use Cocos Creator software for developing other software or tools that's
  1545. used for developing games. You are not granted to publish, distribute,
  1546. sublicense, and/or sell copies of Cocos Creator.
  1547. The software or tools in this License Agreement are licensed, not sold.
  1548. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1549. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1550. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1551. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1552. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1553. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1554. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1555. THE SOFTWARE.
  1556. ****************************************************************************/
  1557. 'use strict';
  1558. const cacheManager = require('./jsb-cache-manager');
  1559. const {
  1560. downloadFile,
  1561. readText,
  1562. readArrayBuffer,
  1563. readJson,
  1564. getUserDataPath,
  1565. initJsbDownloader
  1566. } = require('./jsb-fs-utils');
  1567. const REGEX = /^\w+:\/\/.*/;
  1568. const downloader = cc.assetManager.downloader;
  1569. const parser = cc.assetManager.parser;
  1570. const presets = cc.assetManager.presets;
  1571. downloader.maxConcurrency = 30;
  1572. downloader.maxRequestsPerFrame = 60;
  1573. presets['preload'].maxConcurrency = 15;
  1574. presets['preload'].maxRequestsPerFrame = 30;
  1575. presets['scene'].maxConcurrency = 32;
  1576. presets['scene'].maxRequestsPerFrame = 64;
  1577. presets['bundle'].maxConcurrency = 32;
  1578. presets['bundle'].maxRequestsPerFrame = 64;
  1579. let suffix = 0;
  1580. const failureMap = {};
  1581. const maxRetryCountFromBreakpoint = 5;
  1582. const loadedScripts = {};
  1583. function downloadScript(url, options, onComplete) {
  1584. if (typeof options === 'function') {
  1585. onComplete = options;
  1586. options = null;
  1587. }
  1588. if (loadedScripts[url]) return onComplete && onComplete();
  1589. download(url, function (src, options, onComplete) {
  1590. window.require(src);
  1591. loadedScripts[url] = true;
  1592. onComplete && onComplete(null);
  1593. }, options, options.onFileProgress, onComplete);
  1594. }
  1595. function download(url, func, options, onFileProgress, onComplete) {
  1596. var result = transformUrl(url, options);
  1597. if (result.inLocal) {
  1598. func(result.url, options, onComplete);
  1599. } else if (result.inCache) {
  1600. cacheManager.updateLastTime(url);
  1601. func(result.url, options, function (err, data) {
  1602. if (err) {
  1603. cacheManager.removeCache(url);
  1604. }
  1605. onComplete(err, data);
  1606. });
  1607. } else {
  1608. var time = Date.now();
  1609. var storagePath = '';
  1610. var failureRecord = failureMap[url];
  1611. if (failureRecord) {
  1612. storagePath = failureRecord.storagePath;
  1613. } else if (options.__cacheBundleRoot__) {
  1614. storagePath = `${options.__cacheBundleRoot__}/${time}${suffix++}${cc.path.extname(url)}`;
  1615. } else {
  1616. storagePath = `${time}${suffix++}${cc.path.extname(url)}`;
  1617. }
  1618. downloadFile(url, `${cacheManager.cacheDir}/${storagePath}`, options.header, onFileProgress, function (err, path) {
  1619. if (err) {
  1620. if (failureRecord) {
  1621. failureRecord.retryCount++;
  1622. if (failureRecord.retryCount >= maxRetryCountFromBreakpoint) {
  1623. delete failureMap[url];
  1624. }
  1625. } else {
  1626. failureMap[url] = {
  1627. retryCount: 0,
  1628. storagePath
  1629. };
  1630. }
  1631. onComplete(err, null);
  1632. return;
  1633. }
  1634. delete failureMap[url];
  1635. func(path, options, function (err, data) {
  1636. if (!err) {
  1637. cacheManager.cacheFile(url, storagePath, options.__cacheBundleRoot__);
  1638. }
  1639. onComplete(err, data);
  1640. });
  1641. });
  1642. }
  1643. }
  1644. function transformUrl(url, options) {
  1645. var inLocal = false;
  1646. var inCache = false;
  1647. if (REGEX.test(url)) {
  1648. if (options.reload) {
  1649. return {
  1650. url
  1651. };
  1652. } else {
  1653. var cache = cacheManager.getCache(url);
  1654. if (cache) {
  1655. inCache = true;
  1656. url = cache;
  1657. }
  1658. }
  1659. } else {
  1660. inLocal = true;
  1661. }
  1662. return {
  1663. url,
  1664. inLocal,
  1665. inCache
  1666. };
  1667. }
  1668. function doNothing(content, options, onComplete) {
  1669. onComplete(null, content);
  1670. }
  1671. function downloadAsset(url, options, onComplete) {
  1672. download(url, doNothing, options, options.onFileProgress, onComplete);
  1673. }
  1674. function _getFontFamily(fontHandle) {
  1675. var ttfIndex = fontHandle.lastIndexOf(".ttf");
  1676. if (ttfIndex === -1) return fontHandle;
  1677. var slashPos = fontHandle.lastIndexOf("/");
  1678. var fontFamilyName;
  1679. if (slashPos === -1) {
  1680. fontFamilyName = fontHandle.substring(0, ttfIndex) + "_LABEL";
  1681. } else {
  1682. fontFamilyName = fontHandle.substring(slashPos + 1, ttfIndex) + "_LABEL";
  1683. }
  1684. if (fontFamilyName.indexOf(' ') !== -1) {
  1685. fontFamilyName = '"' + fontFamilyName + '"';
  1686. }
  1687. return fontFamilyName;
  1688. }
  1689. function parseText(url, options, onComplete) {
  1690. readText(url, onComplete);
  1691. }
  1692. function parseJson(url, options, onComplete) {
  1693. readJson(url, onComplete);
  1694. }
  1695. function downloadText(url, options, onComplete) {
  1696. download(url, parseText, options, options.onFileProgress, onComplete);
  1697. }
  1698. function parseArrayBuffer(url, options, onComplete) {
  1699. readArrayBuffer(url, onComplete);
  1700. }
  1701. function downloadJson(url, options, onComplete) {
  1702. download(url, parseJson, options, options.onFileProgress, onComplete);
  1703. }
  1704. function downloadBundle(nameOrUrl, options, onComplete) {
  1705. let bundleName = cc.path.basename(nameOrUrl);
  1706. var version = options.version || downloader.bundleVers[bundleName];
  1707. let url;
  1708. if (REGEX.test(nameOrUrl) || nameOrUrl.startsWith(getUserDataPath())) {
  1709. url = nameOrUrl;
  1710. cacheManager.makeBundleFolder(bundleName);
  1711. } else {
  1712. if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
  1713. url = `${downloader.remoteServerAddress}remote/${bundleName}`;
  1714. cacheManager.makeBundleFolder(bundleName);
  1715. } else {
  1716. url = `assets/${bundleName}`;
  1717. }
  1718. }
  1719. var config = `${url}/cc.config.${version ? version + '.' : ''}json`;
  1720. options.__cacheBundleRoot__ = bundleName;
  1721. downloadJson(config, options, function (err, response) {
  1722. if (err) {
  1723. return onComplete(err, null);
  1724. }
  1725. let out = response;
  1726. out && (out.base = url + '/');
  1727. var js = `${url}/index.${version ? version + '.' : ''}${out.encrypted ? 'jsc' : `js`}`;
  1728. downloadScript(js, options, function (err) {
  1729. if (err) {
  1730. return onComplete(err, null);
  1731. }
  1732. onComplete(null, out);
  1733. });
  1734. });
  1735. }
  1736. ;
  1737. const downloadCCON = (url, options, onComplete) => {
  1738. downloadJson(url, options, (err, json) => {
  1739. if (err) {
  1740. onComplete(err);
  1741. return;
  1742. }
  1743. const cconPreface = cc.internal.parseCCONJson(json);
  1744. const chunkPromises = Promise.all(cconPreface.chunks.map(chunk => new Promise((resolve, reject) => {
  1745. downloadArrayBuffer(`${cc.path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => {
  1746. if (errChunk) {
  1747. reject(errChunk);
  1748. } else {
  1749. resolve(new Uint8Array(chunkBuffer));
  1750. }
  1751. });
  1752. })));
  1753. chunkPromises.then(chunks => {
  1754. const ccon = new cc.internal.CCON(cconPreface.document, chunks);
  1755. onComplete(null, ccon);
  1756. }).catch(err => {
  1757. onComplete(err);
  1758. });
  1759. });
  1760. };
  1761. const downloadCCONB = (url, options, onComplete) => {
  1762. downloadArrayBuffer(url, options, (err, arrayBuffer) => {
  1763. if (err) {
  1764. onComplete(err);
  1765. return;
  1766. }
  1767. try {
  1768. const ccon = cc.internal.decodeCCONBinary(new Uint8Array(arrayBuffer));
  1769. onComplete(null, ccon);
  1770. } catch (err) {
  1771. onComplete(err);
  1772. }
  1773. });
  1774. };
  1775. function downloadArrayBuffer(url, options, onComplete) {
  1776. download(url, parseArrayBuffer, options, options.onFileProgress, onComplete);
  1777. }
  1778. function loadFont(url, options, onComplete) {
  1779. let fontFamilyName = _getFontFamily(url);
  1780. let fontFace = new FontFace(fontFamilyName, "url('" + url + "')");
  1781. document.fonts.add(fontFace);
  1782. fontFace.load();
  1783. fontFace.loaded.then(function () {
  1784. onComplete(null, fontFamilyName);
  1785. }, function () {
  1786. cc.warnID(4933, fontFamilyName);
  1787. onComplete(null, fontFamilyName);
  1788. });
  1789. }
  1790. const originParsePlist = parser.parsePlist;
  1791. let parsePlist = function (url, options, onComplete) {
  1792. readText(url, function (err, file) {
  1793. if (err) return onComplete(err);
  1794. originParsePlist(file, options, onComplete);
  1795. });
  1796. };
  1797. parser.parsePVRTex = downloader.downloadDomImage;
  1798. parser.parsePKMTex = downloader.downloadDomImage;
  1799. parser.parseASTCTex = downloader.downloadDomImage;
  1800. parser.parsePlist = parsePlist;
  1801. downloader.downloadScript = downloadScript;
  1802. function loadAudioPlayer(url, options, onComplete) {
  1803. cc.AudioPlayer.load(url).then(player => {
  1804. const audioMeta = {
  1805. player,
  1806. url,
  1807. duration: player.duration,
  1808. type: player.type
  1809. };
  1810. onComplete(null, audioMeta);
  1811. }).catch(err => {
  1812. onComplete(err);
  1813. });
  1814. }
  1815. downloader.register({
  1816. // JS
  1817. '.js': downloadScript,
  1818. '.jsc': downloadScript,
  1819. // Images
  1820. '.png': downloadAsset,
  1821. '.jpg': downloadAsset,
  1822. '.bmp': downloadAsset,
  1823. '.jpeg': downloadAsset,
  1824. '.gif': downloadAsset,
  1825. '.ico': downloadAsset,
  1826. '.tiff': downloadAsset,
  1827. '.webp': downloadAsset,
  1828. '.image': downloadAsset,
  1829. '.pvr': downloadAsset,
  1830. '.pkm': downloadAsset,
  1831. '.astc': downloadAsset,
  1832. // Audio
  1833. '.mp3': downloadAsset,
  1834. '.ogg': downloadAsset,
  1835. '.wav': downloadAsset,
  1836. '.m4a': downloadAsset,
  1837. '.ccon': downloadCCON,
  1838. '.cconb': downloadCCONB,
  1839. // Video
  1840. '.mp4': downloadAsset,
  1841. '.avi': downloadAsset,
  1842. '.mov': downloadAsset,
  1843. '.mpg': downloadAsset,
  1844. '.mpeg': downloadAsset,
  1845. '.rm': downloadAsset,
  1846. '.rmvb': downloadAsset,
  1847. // Text
  1848. '.txt': downloadAsset,
  1849. '.xml': downloadAsset,
  1850. '.vsh': downloadAsset,
  1851. '.fsh': downloadAsset,
  1852. '.atlas': downloadAsset,
  1853. '.tmx': downloadAsset,
  1854. '.tsx': downloadAsset,
  1855. '.fnt': downloadAsset,
  1856. '.plist': downloadAsset,
  1857. '.json': downloadJson,
  1858. '.ExportJson': downloadAsset,
  1859. '.binary': downloadAsset,
  1860. '.bin': downloadAsset,
  1861. '.dbbin': downloadAsset,
  1862. '.skel': downloadAsset,
  1863. // Font
  1864. '.font': downloadAsset,
  1865. '.eot': downloadAsset,
  1866. '.ttf': downloadAsset,
  1867. '.woff': downloadAsset,
  1868. '.svg': downloadAsset,
  1869. '.ttc': downloadAsset,
  1870. 'bundle': downloadBundle,
  1871. 'default': downloadText
  1872. });
  1873. parser.register({
  1874. // Images
  1875. '.png': downloader.downloadDomImage,
  1876. '.jpg': downloader.downloadDomImage,
  1877. '.bmp': downloader.downloadDomImage,
  1878. '.jpeg': downloader.downloadDomImage,
  1879. '.gif': downloader.downloadDomImage,
  1880. '.ico': downloader.downloadDomImage,
  1881. '.tiff': downloader.downloadDomImage,
  1882. '.webp': downloader.downloadDomImage,
  1883. '.image': downloader.downloadDomImage,
  1884. // Audio
  1885. '.mp3': loadAudioPlayer,
  1886. '.ogg': loadAudioPlayer,
  1887. '.wav': loadAudioPlayer,
  1888. '.m4a': loadAudioPlayer,
  1889. // compressed texture
  1890. '.pvr': downloader.downloadDomImage,
  1891. '.pkm': downloader.downloadDomImage,
  1892. '.astc': downloader.downloadDomImage,
  1893. '.binary': parseArrayBuffer,
  1894. '.bin': parseArrayBuffer,
  1895. '.dbbin': parseArrayBuffer,
  1896. '.skel': parseArrayBuffer,
  1897. // Text
  1898. '.txt': parseText,
  1899. '.xml': parseText,
  1900. '.vsh': parseText,
  1901. '.fsh': parseText,
  1902. '.atlas': parseText,
  1903. '.tmx': parseText,
  1904. '.tsx': parseText,
  1905. '.fnt': parseText,
  1906. '.plist': parsePlist,
  1907. // Font
  1908. '.font': loadFont,
  1909. '.eot': loadFont,
  1910. '.ttf': loadFont,
  1911. '.woff': loadFont,
  1912. '.svg': loadFont,
  1913. '.ttc': loadFont,
  1914. '.ExportJson': parseJson
  1915. });
  1916. cc.assetManager.transformPipeline.append(function (task) {
  1917. var input = task.output = task.input;
  1918. for (var i = 0, l = input.length; i < l; i++) {
  1919. var item = input[i];
  1920. if (item.config) {
  1921. item.options.__cacheBundleRoot__ = item.config.name;
  1922. }
  1923. if (item.ext === '.cconb') {
  1924. item.url = item.url.replace(item.ext, '.bin');
  1925. } else if (item.ext === '.ccon') {
  1926. item.url = item.url.replace(item.ext, '.json');
  1927. }
  1928. }
  1929. });
  1930. var originInit = cc.assetManager.init;
  1931. cc.assetManager.init = function (options) {
  1932. originInit.call(cc.assetManager, options);
  1933. const jsbDownloaderMaxTasks = cc.settings.querySettings('assets', 'jsbDownloaderMaxTasks');
  1934. const jsbDownloaderTimeout = cc.settings.querySettings('assets', 'jsbDownloaderTimeout');
  1935. initJsbDownloader(jsbDownloaderMaxTasks, jsbDownloaderTimeout);
  1936. cacheManager.init();
  1937. };
  1938. },{"./jsb-cache-manager":3,"./jsb-fs-utils":7}],11:[function(require,module,exports){
  1939. "use strict";
  1940. const jsbPhy = globalThis['jsb.physics'];
  1941. jsbPhy.CACHE = {
  1942. trimesh: {},
  1943. convex: {},
  1944. height: {},
  1945. material: {}
  1946. };
  1947. jsbPhy.OBJECT = {
  1948. books: [],
  1949. ptrToObj: {},
  1950. raycastOptions: {
  1951. origin: null,
  1952. unitDir: null,
  1953. distance: 0,
  1954. mask: 0,
  1955. queryTrigger: true
  1956. }
  1957. };
  1958. jsbPhy.CONFIG = {
  1959. heightScale: 1 / 512
  1960. };
  1961. const books = jsbPhy.OBJECT.books;
  1962. const ptrToObj = jsbPhy.OBJECT.ptrToObj;
  1963. const raycastOptions = jsbPhy.OBJECT.raycastOptions;
  1964. const TriggerEventObject = {
  1965. type: 'onTriggerEnter',
  1966. selfCollider: null,
  1967. otherCollider: null,
  1968. impl: null
  1969. };
  1970. const CollisionEventObject = {
  1971. type: 'onCollisionEnter',
  1972. selfCollider: null,
  1973. otherCollider: null,
  1974. contacts: [],
  1975. impl: null
  1976. };
  1977. function emitTriggerEvent(t, c0, c1, impl) {
  1978. TriggerEventObject.type = t;
  1979. TriggerEventObject.impl = impl;
  1980. if (c0.needTriggerEvent) {
  1981. TriggerEventObject.selfCollider = c0;
  1982. TriggerEventObject.otherCollider = c1;
  1983. c0.emit(t, TriggerEventObject);
  1984. }
  1985. if (c1.needTriggerEvent) {
  1986. TriggerEventObject.selfCollider = c1;
  1987. TriggerEventObject.otherCollider = c0;
  1988. c1.emit(t, TriggerEventObject);
  1989. }
  1990. }
  1991. const quat = new cc.Quat();
  1992. const contactsPool = [];
  1993. const contactBufferElementLength = 12;
  1994. class ContactPoint {
  1995. constructor(e) {
  1996. this.event = e;
  1997. this.impl = null;
  1998. this.colliderA = null;
  1999. this.colliderB = null;
  2000. this.index = 0;
  2001. }
  2002. get isBodyA() {
  2003. return this.colliderA.uuid === this.event.selfCollider.uuid;
  2004. }
  2005. getLocalPointOnA(o) {
  2006. this.getWorldPointOnB(o);
  2007. cc.Vec3.subtract(o, o, this.colliderA.node.worldPosition);
  2008. }
  2009. getLocalPointOnB(o) {
  2010. this.getWorldPointOnB(o);
  2011. cc.Vec3.subtract(o, o, this.colliderB.node.worldPosition);
  2012. }
  2013. getWorldPointOnA(o) {
  2014. this.getWorldPointOnB(o);
  2015. }
  2016. getWorldPointOnB(o) {
  2017. const i = this.index * contactBufferElementLength;
  2018. o.x = this.impl[i];
  2019. o.y = this.impl[i + 1];
  2020. o.z = this.impl[i + 2];
  2021. }
  2022. getLocalNormalOnA(o) {
  2023. this.getWorldNormalOnA(o);
  2024. cc.Quat.conjugate(quat, this.colliderA.node.worldRotation);
  2025. cc.Vec3.transformQuat(o, o, quat);
  2026. }
  2027. getLocalNormalOnB(o) {
  2028. this.getWorldNormalOnB(o);
  2029. cc.Quat.conjugate(quat, this.colliderB.node.worldRotation);
  2030. cc.Vec3.transformQuat(out, out, quat);
  2031. }
  2032. getWorldNormalOnA(o) {
  2033. this.getWorldNormalOnB(o);
  2034. if (!this.isBodyA) cc.Vec3.negate(o, o);
  2035. }
  2036. getWorldNormalOnB(o) {
  2037. const i = this.index * contactBufferElementLength + 3;
  2038. o.x = this.impl[i];
  2039. o.y = this.impl[i + 1];
  2040. o.z = this.impl[i + 2];
  2041. }
  2042. }
  2043. function emitCollisionEvent(t, c0, c1, impl, b) {
  2044. CollisionEventObject.type = t;
  2045. CollisionEventObject.impl = impl;
  2046. const contacts = CollisionEventObject.contacts;
  2047. contactsPool.push.apply(contactsPool, contacts);
  2048. contacts.length = 0;
  2049. const contactCount = b.length / contactBufferElementLength;
  2050. for (let i = 0; i < contactCount; i++) {
  2051. const c = contactsPool.length > 0 ? contactsPool.pop() : new ContactPoint(CollisionEventObject);
  2052. c.colliderA = c0;
  2053. c.colliderB = c1;
  2054. c.impl = b;
  2055. c.index = i;
  2056. contacts.push(c);
  2057. }
  2058. if (c0.needCollisionEvent) {
  2059. CollisionEventObject.selfCollider = c0;
  2060. CollisionEventObject.otherCollider = c1;
  2061. c0.emit(t, CollisionEventObject);
  2062. }
  2063. if (c1.needCollisionEvent) {
  2064. CollisionEventObject.selfCollider = c1;
  2065. CollisionEventObject.otherCollider = c0;
  2066. c1.emit(t, CollisionEventObject);
  2067. }
  2068. }
  2069. class PhysicsWorld {
  2070. get impl() {
  2071. return this._impl;
  2072. }
  2073. constructor() {
  2074. this._impl = new jsbPhy.World();
  2075. }
  2076. setGravity(v) {
  2077. this._impl.setGravity(v.x, v.y, v.z);
  2078. }
  2079. setAllowSleep(v) {
  2080. this._impl.setAllowSleep(v);
  2081. }
  2082. setDefaultMaterial(v) {}
  2083. step(f, t, m) {
  2084. // books.forEach((v) => { v.syncToNativeTransform(); });
  2085. this._impl.step(f);
  2086. }
  2087. raycast(r, o, p, rs) {
  2088. raycastOptions.origin = r.o;
  2089. raycastOptions.unitDir = r.d;
  2090. raycastOptions.mask = o.mask >>> 0;
  2091. raycastOptions.distance = o.maxDistance;
  2092. raycastOptions.queryTrigger = !!o.queryTrigger;
  2093. const isHit = this._impl.raycast(raycastOptions);
  2094. if (isHit) {
  2095. const hits = this._impl.raycastResult();
  2096. for (let i = 0; i < hits.length; i++) {
  2097. const hit = hits[i];
  2098. const out = p.add();
  2099. out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2100. rs.push(out);
  2101. }
  2102. }
  2103. return isHit;
  2104. }
  2105. raycastClosest(r, o, out) {
  2106. raycastOptions.origin = r.o;
  2107. raycastOptions.unitDir = r.d;
  2108. raycastOptions.mask = o.mask >>> 0;
  2109. raycastOptions.distance = o.maxDistance;
  2110. raycastOptions.queryTrigger = !!o.queryTrigger;
  2111. const isHit = this._impl.raycastClosest(raycastOptions);
  2112. if (isHit) {
  2113. const hit = this._impl.raycastClosestResult();
  2114. out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2115. }
  2116. return isHit;
  2117. }
  2118. emitEvents() {
  2119. this.emitTriggerEvent();
  2120. this.emitCollisionEvent();
  2121. this._impl.emitEvents();
  2122. }
  2123. syncSceneToPhysics() {
  2124. this._impl.syncSceneToPhysics();
  2125. }
  2126. syncAfterEvents() {// this._impl.syncSceneToPhysics()
  2127. }
  2128. destroy() {
  2129. this._impl.destroy();
  2130. }
  2131. emitTriggerEvent() {
  2132. const teps = this._impl.getTriggerEventPairs();
  2133. const len = teps.length / 3;
  2134. for (let i = 0; i < len; i++) {
  2135. const t = i * 3;
  2136. const sa = ptrToObj[teps[t + 0]];
  2137. const sb = ptrToObj[teps[t + 1]];
  2138. if (!sa || !sb) continue;
  2139. const c0 = sa.collider;
  2140. const c1 = sb.collider;
  2141. if (!(c0 && c0.isValid && c1 && c1.isValid)) continue;
  2142. if (!c0.needTriggerEvent && !c1.needTriggerEvent) continue;
  2143. const state = teps[t + 2];
  2144. if (state === 1) {
  2145. emitTriggerEvent('onTriggerStay', c0, c1, teps);
  2146. } else if (state === 0) {
  2147. emitTriggerEvent('onTriggerEnter', c0, c1, teps);
  2148. } else {
  2149. emitTriggerEvent('onTriggerExit', c0, c1, teps);
  2150. }
  2151. }
  2152. }
  2153. emitCollisionEvent() {
  2154. const ceps = this._impl.getContactEventPairs();
  2155. const len2 = ceps.length / 4;
  2156. for (let i = 0; i < len2; i++) {
  2157. const t = i * 4;
  2158. const sa = ptrToObj[ceps[t + 0]];
  2159. const sb = ptrToObj[ceps[t + 1]];
  2160. if (!sa || !sb) continue;
  2161. const c0 = sa.collider;
  2162. const c1 = sb.collider;
  2163. if (!(c0 && c0.isValid && c1 && c1.isValid)) continue;
  2164. if (!c0.needCollisionEvent && !c1.needCollisionEvent) continue;
  2165. const state = ceps[t + 2];
  2166. if (state === 1) {
  2167. emitCollisionEvent('onCollisionStay', c0, c1, ceps, ceps[t + 3]);
  2168. } else if (state === 0) {
  2169. emitCollisionEvent('onCollisionEnter', c0, c1, ceps, ceps[t + 3]);
  2170. } else {
  2171. emitCollisionEvent('onCollisionExit', c0, c1, ceps, ceps[t + 3]);
  2172. }
  2173. }
  2174. }
  2175. }
  2176. function bookNode(v) {
  2177. if (v._physicsBookIndex === undefined) {
  2178. v._physicsBookIndex = books.length;
  2179. books.push(v);
  2180. }
  2181. }
  2182. function unBookNode(v) {
  2183. const index = v._physicsBookIndex;
  2184. if (index !== undefined) {
  2185. books[index] = books[books.length - 1];
  2186. books[index]._physicsBookIndex = index;
  2187. books.length -= 1;
  2188. v._physicsBookIndex = undefined;
  2189. }
  2190. }
  2191. function updateCollisionMatrix() {
  2192. const phy = cc.PhysicsSystem.instance;
  2193. const world = phy.physicsWorld.impl;
  2194. const cm = phy.collisionMatrix;
  2195. if (cm.updateArray && cm.updateArray.length > 0) {
  2196. cm.updateArray.forEach(e => {
  2197. const key = `${1 << e}`;
  2198. const mask = cm[key];
  2199. world.setCollisionMatrix(e, mask);
  2200. });
  2201. cm.updateArray.length = 0;
  2202. }
  2203. }
  2204. class RigidBody {
  2205. get impl() {
  2206. return this._impl;
  2207. }
  2208. get rigidBody() {
  2209. return this._com;
  2210. }
  2211. get isAwake() {
  2212. return this._impl.isAwake();
  2213. }
  2214. get isSleepy() {
  2215. return false;
  2216. }
  2217. get isSleeping() {
  2218. return this._impl.isSleeping();
  2219. }
  2220. constructor() {
  2221. updateCollisionMatrix();
  2222. this._impl = new jsbPhy.RigidBody();
  2223. this._isUsingCCD = false;
  2224. }
  2225. initialize(v) {
  2226. v.node.updateWorldTransform();
  2227. this._com = v;
  2228. this._impl.initialize(v.node, v.type, v._group);
  2229. bookNode(v.node);
  2230. }
  2231. onEnable() {
  2232. this.setType(this._com.type);
  2233. this.setMass(this._com.mass);
  2234. this.setAllowSleep(this._com.allowSleep);
  2235. this.setLinearDamping(this._com.linearDamping);
  2236. this.setAngularDamping(this._com.angularDamping);
  2237. this.setLinearFactor(this._com.linearFactor);
  2238. this.setAngularFactor(this._com.angularFactor);
  2239. this.useGravity(this._com.useGravity);
  2240. this._impl.onEnable();
  2241. }
  2242. onDisable() {
  2243. this._impl.onDisable();
  2244. }
  2245. onDestroy() {
  2246. unBookNode(this._com.node);
  2247. this._impl.onDestroy();
  2248. }
  2249. setGroup(v) {
  2250. this._impl.setGroup(v);
  2251. }
  2252. getGroup() {
  2253. return this._impl.getGroup();
  2254. }
  2255. addGroup(v) {
  2256. this.setGroup(this.getGroup() | v);
  2257. }
  2258. removeGroup(v) {
  2259. this.setGroup(this.getGroup() & ~v);
  2260. }
  2261. setMask(v) {
  2262. this._impl.setMask(v >>> 0);
  2263. }
  2264. getMask() {
  2265. return this._impl.getMask();
  2266. }
  2267. addMask(v) {
  2268. this.setMask(this.getMask() | v);
  2269. }
  2270. removeMask(v) {
  2271. this.setMask(this.getMask() & ~v);
  2272. }
  2273. setType(v) {
  2274. this._impl.setType(v);
  2275. }
  2276. setMass(v) {
  2277. this._impl.setMass(v);
  2278. }
  2279. setAllowSleep(v) {
  2280. this._impl.setAllowSleep(v);
  2281. }
  2282. setLinearDamping(v) {
  2283. const dt = cc.PhysicsSystem.instance.fixedTimeStep;
  2284. this._impl.setLinearDamping((1 - (1 - v) ** dt) / dt);
  2285. }
  2286. setAngularDamping(v) {
  2287. const dt = cc.PhysicsSystem.instance.fixedTimeStep;
  2288. this._impl.setAngularDamping((1 - (1 - v) ** dt) / dt);
  2289. }
  2290. isUsingCCD() {
  2291. return this._isUsingCCD;
  2292. }
  2293. useCCD(v) {
  2294. this._isUsingCCD = v;
  2295. return this._impl.useCCD(v);
  2296. }
  2297. useGravity(v) {
  2298. this._impl.useGravity(v);
  2299. }
  2300. setLinearFactor(v) {
  2301. this._impl.setLinearFactor(v.x, v.y, v.z);
  2302. }
  2303. setAngularFactor(v) {
  2304. this._impl.setAngularFactor(v.x, v.y, v.z);
  2305. }
  2306. wakeUp() {
  2307. this._impl.wakeUp();
  2308. }
  2309. sleep() {
  2310. this._impl.sleep();
  2311. }
  2312. clearState() {
  2313. this._impl.clearState();
  2314. }
  2315. clearForces() {
  2316. this._impl.clearForces();
  2317. }
  2318. clearVelocity() {
  2319. this._impl.clearVelocity();
  2320. }
  2321. setSleepThreshold(v) {
  2322. this._impl.setSleepThreshold(v);
  2323. }
  2324. getSleepThreshold() {
  2325. return this._impl.getSleepThreshold();
  2326. }
  2327. getLinearVelocity(o) {
  2328. o.set(this._impl.getLinearVelocity());
  2329. }
  2330. setLinearVelocity(v) {
  2331. this._impl.setLinearVelocity(v.x, v.y, v.z);
  2332. }
  2333. getAngularVelocity(o) {
  2334. o.set(this._impl.getAngularVelocity());
  2335. }
  2336. setAngularVelocity(v) {
  2337. this._impl.setAngularVelocity(v.x, v.y, v.z);
  2338. }
  2339. applyForce(f, p) {
  2340. if (p == null) {
  2341. p = cc.Vec3.ZERO;
  2342. }
  2343. this._impl.applyForce(f.x, f.y, f.z, p.x, p.y, p.z);
  2344. }
  2345. applyLocalForce(f, p) {
  2346. if (p == null) {
  2347. p = cc.Vec3.ZERO;
  2348. }
  2349. this._impl.applyLocalForce(f.x, f.y, f.z, p.x, p.y, p.z);
  2350. }
  2351. applyImpulse(f, p) {
  2352. if (p == null) {
  2353. p = cc.Vec3.ZERO;
  2354. }
  2355. this._impl.applyImpulse(f.x, f.y, f.z, p.x, p.y, p.z);
  2356. }
  2357. applyLocalImpulse(f, p) {
  2358. if (p == null) {
  2359. p = cc.Vec3.ZERO;
  2360. }
  2361. this._impl.applyLocalImpulse(f.x, f.y, f.z, p.x, p.y, p.z);
  2362. }
  2363. applyTorque(t) {
  2364. this._impl.applyTorque(t.x, t.y, t.z);
  2365. }
  2366. applyLocalTorque(t) {
  2367. this._impl.applyLocalTorque(t.x, t.y, t.z);
  2368. }
  2369. }
  2370. const ESHAPE_FLAG = {
  2371. NONE: 0,
  2372. QUERY_FILTER: 1 << 0,
  2373. QUERY_SINGLE_HIT: 1 << 2,
  2374. DETECT_TRIGGER_EVENT: 1 << 3,
  2375. DETECT_CONTACT_EVENT: 1 << 4,
  2376. DETECT_CONTACT_POINT: 1 << 5,
  2377. DETECT_CONTACT_CCD: 1 << 6
  2378. };
  2379. class Shape {
  2380. get impl() {
  2381. return this._impl;
  2382. }
  2383. get collider() {
  2384. return this._com;
  2385. }
  2386. get attachedRigidBody() {
  2387. return this._attachedRigidBody;
  2388. }
  2389. constructor() {
  2390. updateCollisionMatrix();
  2391. }
  2392. initialize(v) {
  2393. v.node.updateWorldTransform();
  2394. this._com = v;
  2395. this._impl.initialize(v.node);
  2396. ptrToObj[this._impl.getObjectID()] = this;
  2397. bookNode(v.node);
  2398. }
  2399. onLoad() {
  2400. this.setMaterial(this._com.sharedMaterial);
  2401. this.setCenter(this._com.center);
  2402. this.setAsTrigger(this._com.isTrigger);
  2403. }
  2404. onEnable() {
  2405. this._impl.onEnable();
  2406. }
  2407. onDisable() {
  2408. this._impl.onDisable();
  2409. }
  2410. onDestroy() {
  2411. unBookNode(this._com.node);
  2412. delete ptrToObj[this._impl.getObjectID()];
  2413. ptrToObj[this._impl.getObjectID()] = null;
  2414. this._impl.onDestroy();
  2415. }
  2416. setMaterial(v) {
  2417. const ins = cc.PhysicsSystem.instance;
  2418. if (!v) v = ins.defaultMaterial;
  2419. if (!jsbPhy.CACHE.material[v.id]) {
  2420. jsbPhy.CACHE.material[v.id] = ins.physicsWorld.impl.createMaterial(v.id, v.friction, v.friction, v.restitution, 2, 2);
  2421. }
  2422. this._impl.setMaterial(v.id, v.friction, v.friction, v.restitution, 2, 2);
  2423. }
  2424. setAsTrigger(v) {
  2425. this._impl.setAsTrigger(v);
  2426. }
  2427. setCenter(v) {
  2428. this._impl.setCenter(v.x, v.y, v.z);
  2429. }
  2430. getAABB(v) {
  2431. v.copy(this._impl.getAABB());
  2432. }
  2433. getBoundingSphere(v) {
  2434. v.copy(this._impl.getBoundingSphere());
  2435. }
  2436. updateEventListener() {
  2437. let flag = 0;
  2438. flag |= ESHAPE_FLAG.DETECT_CONTACT_CCD;
  2439. if (this._com.isTrigger) flag |= ESHAPE_FLAG.IS_TRIGGER;
  2440. if (this._com.needTriggerEvent || this._com.needCollisionEvent) flag |= ESHAPE_FLAG.NEED_EVENT;
  2441. this._impl.updateEventListener(flag);
  2442. }
  2443. setGroup(v) {
  2444. this._impl.setGroup(v);
  2445. }
  2446. getGroup() {
  2447. return this._impl.getGroup();
  2448. }
  2449. addGroup(v) {
  2450. this.setGroup(this.getGroup() | v);
  2451. }
  2452. removeGroup(v) {
  2453. this.setGroup(this.getGroup() & ~v);
  2454. }
  2455. setMask(v) {
  2456. this._impl.setMask(v >>> 0);
  2457. }
  2458. getMask() {
  2459. return this._impl.getMask();
  2460. }
  2461. addMask(v) {
  2462. this.setMask(this.getMask() | v);
  2463. }
  2464. removeMask(v) {
  2465. this.setMask(this.getMask() & ~v);
  2466. }
  2467. }
  2468. class SphereShape extends Shape {
  2469. constructor() {
  2470. super();
  2471. this._impl = new jsbPhy.SphereShape();
  2472. }
  2473. updateRadius() {
  2474. this._impl.setRadius(this.collider.radius);
  2475. }
  2476. onLoad() {
  2477. super.onLoad();
  2478. this.updateRadius();
  2479. }
  2480. }
  2481. class BoxShape extends Shape {
  2482. constructor() {
  2483. super();
  2484. this._impl = new jsbPhy.BoxShape();
  2485. }
  2486. updateSize() {
  2487. const v = this.collider.size;
  2488. this._impl.setSize(v.x, v.y, v.z);
  2489. }
  2490. onLoad() {
  2491. super.onLoad();
  2492. this.updateSize();
  2493. }
  2494. }
  2495. class CapsuleShape extends Shape {
  2496. constructor() {
  2497. super();
  2498. this._impl = new jsbPhy.CapsuleShape();
  2499. }
  2500. setRadius(v) {
  2501. this._impl.setRadius(v);
  2502. }
  2503. setDirection(v) {
  2504. this._impl.setDirection(v);
  2505. }
  2506. setCylinderHeight(v) {
  2507. this._impl.setCylinderHeight(v);
  2508. }
  2509. onLoad() {
  2510. super.onLoad();
  2511. this.setRadius(this._com.radius);
  2512. this.setDirection(this._com.direction);
  2513. this.setCylinderHeight(this._com.cylinderHeight);
  2514. }
  2515. }
  2516. class PlaneShape extends Shape {
  2517. constructor() {
  2518. super();
  2519. this._impl = new jsbPhy.PlaneShape();
  2520. }
  2521. setConstant(v) {
  2522. this._impl.setConstant(v);
  2523. }
  2524. setNormal(v) {
  2525. this._impl.setNormal(v.x, v.y, v.z);
  2526. }
  2527. onLoad() {
  2528. super.onLoad();
  2529. this.setNormal(this._com.normal);
  2530. this.setConstant(this._com.constant);
  2531. }
  2532. }
  2533. function getConvexMesh(v) {
  2534. if (!jsbPhy.CACHE.convex[v._uuid]) {
  2535. const posArr = cc.physics.utils.shrinkPositions(v.readAttribute(0, 'a_position'));
  2536. const world = cc.PhysicsSystem.instance.physicsWorld.impl;
  2537. const convex = {
  2538. positions: new Float32Array(posArr),
  2539. positionLength: posArr.length / 3
  2540. };
  2541. jsbPhy.CACHE.convex[v._uuid] = world.createConvex(convex);
  2542. }
  2543. return jsbPhy.CACHE.convex[v._uuid];
  2544. }
  2545. function getTriangleMesh(v) {
  2546. if (!jsbPhy.CACHE.trimesh[v._uuid]) {
  2547. const indArr = v.readIndices(0); // const posArr = cc.physics.utils.shrinkPositions(v.readAttribute(0, 'a_position'));
  2548. const posArr = v.readAttribute(0, 'a_position');
  2549. const world = cc.PhysicsSystem.instance.physicsWorld.impl;
  2550. const trimesh = {
  2551. positions: new Float32Array(posArr),
  2552. positionLength: posArr.length / 3,
  2553. triangles: new Uint16Array(indArr),
  2554. triangleLength: indArr.length / 3,
  2555. isU16: true
  2556. };
  2557. jsbPhy.CACHE.trimesh[v._uuid] = world.createTrimesh(trimesh);
  2558. }
  2559. return jsbPhy.CACHE.trimesh[v._uuid];
  2560. }
  2561. function getHeightField(v) {
  2562. if (!jsbPhy.CACHE.height[v._uuid]) {
  2563. const rows = v.getVertexCountI();
  2564. const columns = v.getVertexCountJ();
  2565. const samples = new Int16Array(rows * columns);
  2566. const heightScale = jsbPhy.CONFIG.heightScale;
  2567. for (let i = 0; i < rows; i++) {
  2568. for (let j = 0; j < columns; j++) {
  2569. samples[j + i * columns] = v.getHeight(i, j) / heightScale;
  2570. }
  2571. }
  2572. const height = {
  2573. rows,
  2574. columns,
  2575. samples
  2576. };
  2577. const world = cc.PhysicsSystem.instance.physicsWorld.impl;
  2578. jsbPhy.CACHE.height[v._uuid] = world.createHeightField(height);
  2579. }
  2580. return jsbPhy.CACHE.height[v._uuid];
  2581. }
  2582. class CylinderShape extends Shape {
  2583. constructor() {
  2584. super();
  2585. this._impl = new jsbPhy.CylinderShape();
  2586. }
  2587. setRadius(v) {
  2588. this.updateGeometry();
  2589. }
  2590. setDirection(v) {
  2591. this.updateGeometry();
  2592. }
  2593. setHeight(v) {
  2594. this.updateGeometry();
  2595. }
  2596. updateGeometry() {
  2597. this._impl.setCylinder(this._com.radius, this._com.height, this._com.direction);
  2598. }
  2599. initialize(v) {
  2600. if (!jsbPhy.CACHE.convex.CYLINDER) {
  2601. const primitive = cc.physics.utils.cylinder(0.5, 0.5, 2, {
  2602. radialSegments: 32,
  2603. heightSegments: 1
  2604. });
  2605. const posArr = cc.physics.utils.shrinkPositions(primitive.positions);
  2606. const convex = {
  2607. positions: new Float32Array(posArr),
  2608. positionLength: posArr.length / 3
  2609. };
  2610. const pxObjectID = cc.PhysicsSystem.instance.physicsWorld.impl.createConvex(convex);
  2611. jsbPhy.CACHE.convex.CYLINDER = pxObjectID;
  2612. }
  2613. this._com = v;
  2614. this._impl.setCylinder(v.radius, v.height, v.direction);
  2615. this._impl.setConvex(jsbPhy.CACHE.convex.CYLINDER);
  2616. super.initialize(v);
  2617. }
  2618. }
  2619. class ConeShape extends Shape {
  2620. constructor() {
  2621. super();
  2622. this._impl = new jsbPhy.ConeShape();
  2623. }
  2624. setRadius(v) {
  2625. this.updateGeometry();
  2626. }
  2627. setDirection(v) {
  2628. this.updateGeometry();
  2629. }
  2630. setHeight(v) {
  2631. this.updateGeometry();
  2632. }
  2633. updateGeometry() {
  2634. this._impl.setCone(this._com.radius, this._com.height, this._com.direction);
  2635. }
  2636. initialize(v) {
  2637. if (!jsbPhy.CACHE.convex.CONE) {
  2638. const primitive = cc.physics.utils.cylinder(0, 0.5, 1, {
  2639. radialSegments: 32,
  2640. heightSegments: 1
  2641. });
  2642. const posArr = cc.physics.utils.shrinkPositions(primitive.positions);
  2643. const convex = {
  2644. positions: new Float32Array(posArr),
  2645. positionLength: posArr.length / 3
  2646. };
  2647. const pxObjectID = cc.PhysicsSystem.instance.physicsWorld.impl.createConvex(convex);
  2648. jsbPhy.CACHE.convex.CONE = pxObjectID;
  2649. }
  2650. this._com = v;
  2651. this._impl.setCone(v.radius, v.height, v.direction);
  2652. this._impl.setConvex(jsbPhy.CACHE.convex.CONE);
  2653. super.initialize(v);
  2654. }
  2655. }
  2656. class TrimeshShape extends Shape {
  2657. constructor() {
  2658. super();
  2659. this._impl = new jsbPhy.TrimeshShape();
  2660. }
  2661. setConvex(v) {
  2662. this._impl.useConvex(v);
  2663. }
  2664. setMesh(v) {
  2665. if (!v) return;
  2666. const isConvex = this._com.convex;
  2667. this._impl.useConvex(isConvex);
  2668. const pxObjectID = isConvex ? getConvexMesh(v) : getTriangleMesh(v);
  2669. this._impl.setMesh(pxObjectID);
  2670. }
  2671. initialize(v) {
  2672. this._com = v;
  2673. this.setConvex(v.convex);
  2674. this.setMesh(v.mesh);
  2675. super.initialize(v);
  2676. }
  2677. }
  2678. class TerrainShape extends Shape {
  2679. constructor() {
  2680. super();
  2681. this._impl = new jsbPhy.TerrainShape();
  2682. }
  2683. setTerrain(v) {
  2684. if (!v) return;
  2685. const pxObjectID = getHeightField(v);
  2686. this._impl.setTerrain(pxObjectID, v.tileSize, v.tileSize, jsbPhy.CONFIG.heightScale);
  2687. }
  2688. initialize(v) {
  2689. this._com = v;
  2690. this.setTerrain(v.terrain);
  2691. super.initialize(v);
  2692. }
  2693. }
  2694. class Joint {
  2695. get impl() {
  2696. return this._impl;
  2697. }
  2698. get joint() {
  2699. return this._com;
  2700. }
  2701. setEnableCollision(v) {
  2702. this._impl.setEnableCollision(v);
  2703. }
  2704. setConnectedBody(v) {
  2705. this._impl.setConnectedBody(v ? v.body.impl.getObjectID() : 0);
  2706. }
  2707. initialize(v) {
  2708. this._com = v;
  2709. this._impl.initialize(v.node);
  2710. ptrToObj[this._impl.getObjectID()] = this;
  2711. this.onLoad();
  2712. }
  2713. onLoad() {
  2714. this.setConnectedBody(this._com.connectedBody);
  2715. this.setEnableCollision(this._com.enableCollision);
  2716. }
  2717. onEnable() {
  2718. this._impl.onEnable();
  2719. }
  2720. onDisable() {
  2721. this._impl.onDisable();
  2722. }
  2723. onDestroy() {
  2724. delete ptrToObj[this._impl.getObjectID()];
  2725. ptrToObj[this._impl.getObjectID()] = null;
  2726. this._impl.onDestroy();
  2727. }
  2728. }
  2729. class DistanceJoint extends Joint {
  2730. constructor() {
  2731. super();
  2732. this._impl = new jsbPhy.DistanceJoint();
  2733. }
  2734. setPivotA(v) {
  2735. this._impl.setPivotA(v.x, v.y, v.z);
  2736. }
  2737. setPivotB(v) {
  2738. this._impl.setPivotB(v.x, v.y, v.z);
  2739. }
  2740. onLoad() {
  2741. super.onLoad();
  2742. this.setPivotA(this._com.pivotA);
  2743. this.setPivotB(this._com.pivotB);
  2744. }
  2745. }
  2746. class RevoluteJoint extends Joint {
  2747. constructor() {
  2748. super();
  2749. this._impl = new jsbPhy.RevoluteJoint();
  2750. }
  2751. setAxis(v) {
  2752. this._impl.setAxis(v.x, v.y, v.z);
  2753. }
  2754. setPivotA(v) {
  2755. this._impl.setPivotA(v.x, v.y, v.z);
  2756. }
  2757. setPivotB(v) {
  2758. this._impl.setPivotB(v.x, v.y, v.z);
  2759. }
  2760. onLoad() {
  2761. super.onLoad();
  2762. this.setAxis(this._com.axis);
  2763. this.setPivotA(this._com.pivotA);
  2764. this.setPivotB(this._com.pivotB);
  2765. }
  2766. }
  2767. cc.physics.selector.register('physx', {
  2768. PhysicsWorld,
  2769. RigidBody,
  2770. SphereShape,
  2771. BoxShape,
  2772. PlaneShape,
  2773. CapsuleShape,
  2774. ConeShape,
  2775. CylinderShape,
  2776. TrimeshShape,
  2777. TerrainShape,
  2778. PointToPointConstraint: DistanceJoint,
  2779. HingeConstraint: RevoluteJoint
  2780. });
  2781. },{}],12:[function(require,module,exports){
  2782. "use strict";
  2783. /****************************************************************************
  2784. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  2785. http://www.cocos.com
  2786. Permission is hereby granted, free of charge, to any person obtaining a copy
  2787. of this software and associated engine source code (the "Software"), a limited,
  2788. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  2789. to use Cocos Creator solely to develop games on your target platforms. You shall
  2790. not use Cocos Creator software for developing other software or tools that's
  2791. used for developing games. You are not granted to publish, distribute,
  2792. sublicense, and/or sell copies of Cocos Creator.
  2793. The software or tools in this License Agreement are licensed, not sold.
  2794. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  2795. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2796. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2797. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2798. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2799. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2800. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  2801. THE SOFTWARE.
  2802. ****************************************************************************/
  2803. const cacheManager = require('./jsb-cache-manager'); // @ts-expect-error jsb polyfills
  2804. (function () {
  2805. if (window.spine === undefined || window.middleware === undefined) return;
  2806. if (cc.internal.SpineSkeletonData === undefined) return;
  2807. const spine = window.spine;
  2808. const middleware = window.middleware;
  2809. middleware.generateGetSet(spine); // spine global time scale
  2810. Object.defineProperty(spine, 'timeScale', {
  2811. get() {
  2812. return this._timeScale;
  2813. },
  2814. set(value) {
  2815. this._timeScale = value;
  2816. spine.SkeletonAnimation.setGlobalTimeScale(value);
  2817. },
  2818. configurable: true
  2819. });
  2820. const _slotColor = cc.color(0, 0, 255, 255);
  2821. const _boneColor = cc.color(255, 0, 0, 255);
  2822. const _meshColor = cc.color(255, 255, 0, 255);
  2823. const _originColor = cc.color(0, 255, 0, 255);
  2824. const skeletonDataProto = cc.internal.SpineSkeletonData.prototype;
  2825. let _gTextureIdx = 1;
  2826. const _textureKeyMap = {};
  2827. const _textureMap = new WeakMap();
  2828. const skeletonDataMgr = spine.SkeletonDataMgr.getInstance();
  2829. spine.skeletonDataMgr = skeletonDataMgr;
  2830. skeletonDataMgr.setDestroyCallback(textureIndex => {
  2831. if (!textureIndex) return;
  2832. const texKey = _textureKeyMap[textureIndex];
  2833. if (texKey && _textureMap.has(texKey)) {
  2834. _textureMap.delete(texKey);
  2835. delete _textureKeyMap[textureIndex];
  2836. }
  2837. });
  2838. const skeletonCacheMgr = spine.SkeletonCacheMgr.getInstance();
  2839. spine.skeletonCacheMgr = skeletonCacheMgr;
  2840. skeletonDataProto.destroy = function () {
  2841. this.reset();
  2842. skeletonCacheMgr.removeSkeletonCache(this._uuid);
  2843. cc.Asset.prototype.destroy.call(this);
  2844. };
  2845. skeletonDataProto.reset = function () {
  2846. if (this._skeletonCache) {
  2847. spine.disposeSkeletonData(this._uuid);
  2848. this._jsbTextures = null;
  2849. this._skeletonCache = null;
  2850. }
  2851. this._atlasCache = null;
  2852. };
  2853. skeletonDataProto.getRuntimeData = function () {
  2854. if (!this._skeletonCache) {
  2855. this.init();
  2856. }
  2857. return this._skeletonCache;
  2858. };
  2859. skeletonDataProto.init = function () {
  2860. if (this._skeletonCache) return;
  2861. const uuid = this._uuid;
  2862. if (!uuid) {
  2863. cc.errorID(7504);
  2864. return;
  2865. }
  2866. const atlasText = this.atlasText;
  2867. if (!atlasText) {
  2868. cc.errorID(7508, this.name);
  2869. return;
  2870. }
  2871. const textures = this.textures;
  2872. const textureNames = this.textureNames;
  2873. if (!(textures && textures.length > 0 && textureNames && textureNames.length > 0)) {
  2874. cc.errorID(7507, this.name);
  2875. return;
  2876. }
  2877. const jsbTextures = {};
  2878. for (let i = 0; i < textures.length; ++i) {
  2879. const texture = textures[i];
  2880. const textureIdx = this.recordTexture(texture);
  2881. const spTex = new middleware.Texture2D();
  2882. spTex.setRealTextureIndex(textureIdx);
  2883. spTex.setPixelsWide(texture.width);
  2884. spTex.setPixelsHigh(texture.height);
  2885. spTex.setRealTexture(texture);
  2886. jsbTextures[textureNames[i]] = spTex;
  2887. }
  2888. this._jsbTextures = jsbTextures;
  2889. let filePath = null;
  2890. if (this.skeletonJsonStr) {
  2891. filePath = this.skeletonJsonStr;
  2892. } else {
  2893. filePath = cacheManager.getCache(this.nativeUrl) || this.nativeUrl;
  2894. }
  2895. this._skeletonCache = spine.initSkeletonData(uuid, filePath, atlasText, jsbTextures, this.scale);
  2896. if (this._skeletonCache) {
  2897. this.width = this._skeletonCache.getWidth();
  2898. this.height = this._skeletonCache.getHeight();
  2899. }
  2900. };
  2901. skeletonDataProto.recordTexture = function (texture) {
  2902. const index = _gTextureIdx;
  2903. const texKey = _textureKeyMap[index] = {
  2904. key: index
  2905. };
  2906. _textureMap.set(texKey, texture);
  2907. _gTextureIdx++;
  2908. return index;
  2909. };
  2910. skeletonDataProto.getTextureByIndex = function (textureIdx) {
  2911. const texKey = _textureKeyMap[textureIdx];
  2912. if (!texKey) return null;
  2913. return _textureMap.get(texKey);
  2914. };
  2915. const animation = spine.SkeletonAnimation.prototype; // The methods are added to be compatibility with old versions.
  2916. animation.setCompleteListener = function (listener) {
  2917. this._compeleteListener = listener;
  2918. this.setCompleteListenerNative(function (trackEntry) {
  2919. const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
  2920. this._compeleteListener && this._compeleteListener(trackEntry, loopCount);
  2921. });
  2922. }; // The methods are added to be compatibility with old versions.
  2923. animation.setTrackCompleteListener = function (trackEntry, listener) {
  2924. this._trackCompeleteListener = listener;
  2925. this.setTrackCompleteListenerNative(trackEntry, function (trackEntryNative) {
  2926. const loopCount = Math.floor(trackEntryNative.trackTime / trackEntryNative.animationEnd);
  2927. this._trackCompeleteListener && this._trackCompeleteListener(trackEntryNative, loopCount);
  2928. });
  2929. }; // Temporary solution before upgrade the Spine API
  2930. animation.setAnimationListener = function (target, callback) {
  2931. this._target = target;
  2932. this._callback = callback; // eslint-disable-next-line no-undef
  2933. const AnimationEventType = legacyCC.internal.SpineAnimationEventType;
  2934. this.setStartListener(function (trackEntry) {
  2935. if (this._target && this._callback) {
  2936. this._callback.call(this._target, this, trackEntry, AnimationEventType.START, null, 0);
  2937. }
  2938. });
  2939. this.setInterruptListener(function (trackEntry) {
  2940. if (this._target && this._callback) {
  2941. this._callback.call(this._target, this, trackEntry, AnimationEventType.INTERRUPT, null, 0);
  2942. }
  2943. });
  2944. this.setEndListener(function (trackEntry) {
  2945. if (this._target && this._callback) {
  2946. this._callback.call(this._target, this, trackEntry, AnimationEventType.END, null, 0);
  2947. }
  2948. });
  2949. this.setDisposeListener(function (trackEntry) {
  2950. if (this._target && this._callback) {
  2951. this._callback.call(this._target, this, trackEntry, AnimationEventType.DISPOSE, null, 0);
  2952. }
  2953. });
  2954. this.setCompleteListener(function (trackEntry, loopCount) {
  2955. if (this._target && this._callback) {
  2956. this._callback.call(this._target, this, trackEntry, AnimationEventType.COMPLETE, null, loopCount);
  2957. }
  2958. });
  2959. this.setEventListener(function (trackEntry, event) {
  2960. if (this._target && this._callback) {
  2961. this._callback.call(this._target, this, trackEntry, AnimationEventType.EVENT, event, 0);
  2962. }
  2963. });
  2964. };
  2965. const skeleton = cc.internal.SpineSkeleton.prototype;
  2966. const AnimationCacheMode = cc.internal.SpineSkeleton.AnimationCacheMode;
  2967. Object.defineProperty(skeleton, 'paused', {
  2968. get() {
  2969. return this._paused || false;
  2970. },
  2971. set(value) {
  2972. this._paused = value;
  2973. if (this._nativeSkeleton) {
  2974. this._nativeSkeleton.paused(value);
  2975. }
  2976. }
  2977. });
  2978. Object.defineProperty(skeleton, 'premultipliedAlpha', {
  2979. get() {
  2980. if (this._premultipliedAlpha === undefined) {
  2981. return true;
  2982. }
  2983. return this._premultipliedAlpha;
  2984. },
  2985. set(value) {
  2986. this._premultipliedAlpha = value;
  2987. if (this._nativeSkeleton) {
  2988. this._nativeSkeleton.setOpacityModifyRGB(this._premultipliedAlpha);
  2989. }
  2990. }
  2991. });
  2992. Object.defineProperty(skeleton, 'timeScale', {
  2993. get() {
  2994. if (this._timeScale === undefined) return 1.0;
  2995. return this._timeScale;
  2996. },
  2997. set(value) {
  2998. this._timeScale = value;
  2999. if (this._nativeSkeleton) {
  3000. this._nativeSkeleton.setTimeScale(this._timeScale);
  3001. }
  3002. }
  3003. });
  3004. const _updateDebugDraw = skeleton._updateDebugDraw;
  3005. skeleton._updateDebugDraw = function () {
  3006. _updateDebugDraw.call(this);
  3007. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3008. this._nativeSkeleton.setDebugMeshEnabled(this.debugMesh);
  3009. this._nativeSkeleton.setDebugSlotsEnabled(this.debugSlots);
  3010. this._nativeSkeleton.setDebugBonesEnabled(this.debugBones);
  3011. }
  3012. };
  3013. const _updateUseTint = skeleton._updateUseTint;
  3014. skeleton._updateUseTint = function () {
  3015. _updateUseTint.call(this);
  3016. if (this._nativeSkeleton) {
  3017. this._nativeSkeleton.setUseTint(this.useTint);
  3018. }
  3019. };
  3020. skeleton._updateBatch = function () {
  3021. if (this._nativeSkeleton) {
  3022. this._renderEntity.setUseLocal(!this.enableBatch);
  3023. this._nativeSkeleton.setBatchEnabled(this.enableBatch);
  3024. this.markForUpdateRenderData();
  3025. }
  3026. };
  3027. skeleton.setSkeletonData = function (skeletonData) {
  3028. if (skeletonData.width != null && skeletonData.height != null) {
  3029. const uiTrans = this.node._uiProps.uiTransformComp;
  3030. uiTrans.setContentSize(skeletonData.width, skeletonData.height);
  3031. }
  3032. const uuid = skeletonData._uuid;
  3033. if (!uuid) {
  3034. cc.errorID(7504);
  3035. return;
  3036. }
  3037. const texValues = skeletonData.textures;
  3038. const texKeys = skeletonData.textureNames;
  3039. if (!(texValues && texValues.length > 0 && texKeys && texKeys.length > 0)) {
  3040. cc.errorID(7507, skeletonData.name);
  3041. return;
  3042. }
  3043. if (this._nativeSkeleton) {
  3044. this._nativeSkeleton.stopSchedule();
  3045. this._nativeSkeleton._comp = null;
  3046. this._nativeSkeleton = null;
  3047. }
  3048. let nativeSkeleton = null;
  3049. if (this.isAnimationCached()) {
  3050. nativeSkeleton = new spine.SkeletonCacheAnimation(uuid, this._cacheMode === AnimationCacheMode.SHARED_CACHE);
  3051. } else {
  3052. nativeSkeleton = new spine.SkeletonAnimation();
  3053. try {
  3054. spine.initSkeletonRenderer(nativeSkeleton, uuid);
  3055. } catch (e) {
  3056. cc._throw(e);
  3057. return;
  3058. }
  3059. nativeSkeleton.setDebugSlotsEnabled(this.debugSlots);
  3060. nativeSkeleton.setDebugMeshEnabled(this.debugMesh);
  3061. nativeSkeleton.setDebugBonesEnabled(this.debugBones);
  3062. }
  3063. this._nativeSkeleton = nativeSkeleton;
  3064. nativeSkeleton._comp = this;
  3065. nativeSkeleton.setUseTint(this.useTint);
  3066. nativeSkeleton.setOpacityModifyRGB(this.premultipliedAlpha);
  3067. nativeSkeleton.setTimeScale(this.timeScale);
  3068. nativeSkeleton.setBatchEnabled(this.enableBatch);
  3069. const compColor = this.color;
  3070. nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  3071. const materialTemplate = this.getMaterialTemplate();
  3072. nativeSkeleton.setMaterial(materialTemplate);
  3073. this._renderEntity.setUseLocal(!this.enableBatch);
  3074. nativeSkeleton.setRenderEntity(this._renderEntity.nativeObj);
  3075. this._skeleton = nativeSkeleton.getSkeleton(); // init skeleton listener
  3076. this._startListener && this.setStartListener(this._startListener);
  3077. this._endListener && this.setEndListener(this._endListener);
  3078. this._completeListener && this.setCompleteListener(this._completeListener);
  3079. this._eventListener && this.setEventListener(this._eventListener);
  3080. this._interruptListener && this.setInterruptListener(this._interruptListener);
  3081. this._disposeListener && this.setDisposeListener(this._disposeListener);
  3082. this._sharedBufferOffset = nativeSkeleton.getSharedBufferOffset();
  3083. this._useAttach = false;
  3084. this.markForUpdateRenderData();
  3085. };
  3086. skeleton._updateColor = function () {
  3087. if (this._nativeSkeleton) {
  3088. const compColor = this.color;
  3089. this._nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  3090. this.markForUpdateRenderData();
  3091. }
  3092. };
  3093. skeleton.setAnimationStateData = function (stateData) {
  3094. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3095. this._stateData = stateData;
  3096. this._nativeSkeleton.setAnimationStateData(stateData);
  3097. }
  3098. };
  3099. const _onEnable = skeleton.onEnable;
  3100. skeleton.onEnable = function () {
  3101. if (_onEnable) {
  3102. _onEnable.call(this);
  3103. }
  3104. if (this._nativeSkeleton) {
  3105. this._nativeSkeleton.onEnable();
  3106. }
  3107. middleware.retain();
  3108. };
  3109. const _onDisable = skeleton.onDisable;
  3110. skeleton.onDisable = function () {
  3111. if (_onDisable) {
  3112. _onDisable.call(this);
  3113. }
  3114. if (this._nativeSkeleton) {
  3115. this._nativeSkeleton.onDisable();
  3116. }
  3117. middleware.release();
  3118. };
  3119. skeleton.setVertexEffectDelegate = function (effectDelegate) {
  3120. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3121. this._nativeSkeleton.setVertexEffectDelegate(effectDelegate);
  3122. }
  3123. }; // eslint-disable-next-line no-unused-vars
  3124. skeleton.updateAnimation = function (dt) {
  3125. const nativeSkeleton = this._nativeSkeleton;
  3126. if (!nativeSkeleton) return;
  3127. const node = this.node;
  3128. if (!node) return;
  3129. if (this.__preColor__ === undefined || !this.color.equals(this.__preColor__)) {
  3130. const compColor = this.color;
  3131. nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  3132. this.__preColor__ = compColor;
  3133. }
  3134. const socketNodes = this.socketNodes;
  3135. if (!this._useAttach && socketNodes.size > 0) {
  3136. this._useAttach = true;
  3137. nativeSkeleton.setAttachEnabled(true);
  3138. }
  3139. if (!this.isAnimationCached() && (this.debugBones || this.debugSlots || this.debugMesh) && this._debugRenderer) {
  3140. const graphics = this._debugRenderer;
  3141. graphics.clear();
  3142. graphics.lineWidth = 5;
  3143. const debugData = this._debugData || nativeSkeleton.getDebugData();
  3144. if (!debugData) return;
  3145. let debugIdx = 0;
  3146. let debugType = 0;
  3147. let debugLen = 0;
  3148. debugType = debugData[debugIdx++];
  3149. while (debugType !== 0) {
  3150. debugLen = debugData[debugIdx++];
  3151. switch (debugType) {
  3152. case 1:
  3153. // slots
  3154. graphics.strokeColor = _slotColor;
  3155. for (let i = 0; i < debugLen; i += 8) {
  3156. graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]);
  3157. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  3158. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  3159. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  3160. graphics.close();
  3161. graphics.stroke();
  3162. }
  3163. break;
  3164. case 2:
  3165. // mesh
  3166. graphics.strokeColor = _meshColor;
  3167. for (let i = 0; i < debugLen; i += 6) {
  3168. graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]);
  3169. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  3170. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  3171. graphics.close();
  3172. graphics.stroke();
  3173. }
  3174. break;
  3175. case 3:
  3176. // bones
  3177. graphics.strokeColor = _boneColor;
  3178. graphics.fillColor = _slotColor; // Root bone color is same as slot color.
  3179. for (let i = 0; i < debugLen; i += 4) {
  3180. const bx = debugData[debugIdx++];
  3181. const by = debugData[debugIdx++];
  3182. const x = debugData[debugIdx++];
  3183. const y = debugData[debugIdx++]; // Bone lengths.
  3184. graphics.moveTo(bx, by);
  3185. graphics.lineTo(x, y);
  3186. graphics.stroke(); // Bone origins.
  3187. graphics.circle(bx, by, Math.PI * 1.5);
  3188. graphics.fill();
  3189. if (i === 0) {
  3190. graphics.fillColor = _originColor;
  3191. }
  3192. }
  3193. break;
  3194. default:
  3195. return;
  3196. }
  3197. debugType = debugData[debugIdx++];
  3198. }
  3199. }
  3200. };
  3201. skeleton.updateWorldTransform = function () {
  3202. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3203. this._nativeSkeleton.updateWorldTransform();
  3204. }
  3205. };
  3206. skeleton.setToSetupPose = function () {
  3207. if (this._nativeSkeleton) {
  3208. this._nativeSkeleton.setToSetupPose();
  3209. }
  3210. };
  3211. skeleton.setBonesToSetupPose = function () {
  3212. if (this._nativeSkeleton) {
  3213. this._nativeSkeleton.setBonesToSetupPose();
  3214. }
  3215. };
  3216. skeleton.setSlotsToSetupPose = function () {
  3217. if (this._nativeSkeleton) {
  3218. this._nativeSkeleton.setSlotsToSetupPose();
  3219. }
  3220. };
  3221. skeleton.setSlotsRange = function (startSlotIndex, endSlotIndex) {
  3222. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3223. this._nativeSkeleton.setSlotsRange(startSlotIndex, endSlotIndex);
  3224. }
  3225. };
  3226. skeleton.updateAnimationCache = function (animName) {
  3227. if (!this.isAnimationCached()) return;
  3228. if (this._nativeSkeleton) {
  3229. if (animName) {
  3230. this._nativeSkeleton.updateAnimationCache(animName);
  3231. } else {
  3232. this._nativeSkeleton.updateAllAnimationCache();
  3233. }
  3234. }
  3235. };
  3236. skeleton.invalidAnimationCache = function () {
  3237. if (!this.isAnimationCached()) return;
  3238. if (this._nativeSkeleton) {
  3239. this._nativeSkeleton.updateAllAnimationCache();
  3240. }
  3241. };
  3242. skeleton.findBone = function (boneName) {
  3243. if (this._nativeSkeleton) return this._nativeSkeleton.findBone(boneName);
  3244. return null;
  3245. };
  3246. skeleton.findSlot = function (slotName) {
  3247. if (this._nativeSkeleton) return this._nativeSkeleton.findSlot(slotName);
  3248. return null;
  3249. };
  3250. skeleton.setSkin = function (skinName) {
  3251. if (this._nativeSkeleton) return this._nativeSkeleton.setSkin(skinName);
  3252. return null;
  3253. };
  3254. skeleton.getAttachment = function (slotName, attachmentName) {
  3255. if (this._nativeSkeleton) return this._nativeSkeleton.getAttachment(slotName, attachmentName);
  3256. return null;
  3257. };
  3258. skeleton.setAttachment = function (slotName, attachmentName) {
  3259. this._nativeSkeleton && this._nativeSkeleton.setAttachment(slotName, attachmentName);
  3260. }; // eslint-disable-next-line no-unused-vars
  3261. skeleton.getTextureAtlas = function (regionAttachment) {
  3262. cc.warn('Spine Skeleton getTextureAtlas not support in native');
  3263. return null;
  3264. };
  3265. skeleton.setMix = function (fromAnimation, toAnimation, duration) {
  3266. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3267. this._nativeSkeleton.setMix(fromAnimation, toAnimation, duration);
  3268. }
  3269. };
  3270. skeleton.setAnimation = function (trackIndex, name, loop) {
  3271. const strName = name.toString();
  3272. this._animationName = strName;
  3273. this._playTimes = loop ? 0 : 1;
  3274. let res = null;
  3275. if (this._nativeSkeleton) {
  3276. if (this.isAnimationCached()) {
  3277. res = this._nativeSkeleton.setAnimation(strName, loop);
  3278. } else {
  3279. res = this._nativeSkeleton.setAnimation(trackIndex, strName, loop);
  3280. }
  3281. /**
  3282. * note: since native spine animation update called after Director.EVENT_BEFORE_UPDATE
  3283. * and before setAnimation. it's need to update native animation to first frame directly.
  3284. */
  3285. this._nativeSkeleton.update(0);
  3286. }
  3287. return res;
  3288. };
  3289. skeleton.addAnimation = function (trackIndex, name, loop, delay) {
  3290. if (this._nativeSkeleton) {
  3291. delay = delay || 0;
  3292. if (this.isAnimationCached()) {
  3293. return this._nativeSkeleton.addAnimation(name, loop, delay);
  3294. } else {
  3295. return this._nativeSkeleton.addAnimation(trackIndex, name, loop, delay);
  3296. }
  3297. }
  3298. return null;
  3299. };
  3300. skeleton.findAnimation = function (name) {
  3301. if (this._nativeSkeleton) return this._nativeSkeleton.findAnimation(name);
  3302. return null;
  3303. };
  3304. skeleton.getCurrent = function (trackIndex) {
  3305. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3306. return this._nativeSkeleton.getCurrent(trackIndex);
  3307. }
  3308. return null;
  3309. };
  3310. skeleton.clearTracks = function () {
  3311. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3312. this._nativeSkeleton.clearTracks();
  3313. }
  3314. };
  3315. skeleton.clearTrack = function (trackIndex) {
  3316. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3317. this._nativeSkeleton.clearTrack(trackIndex);
  3318. }
  3319. };
  3320. skeleton.setStartListener = function (listener) {
  3321. this._startListener = listener;
  3322. if (this._nativeSkeleton) {
  3323. if (this.isAnimationCached()) {
  3324. this._nativeSkeleton.setStartListener(function (animationName) {
  3325. const self = this._comp;
  3326. self._startEntry.animation.name = animationName;
  3327. self._startListener && self._startListener(self._startEntry);
  3328. });
  3329. } else {
  3330. this._nativeSkeleton.setStartListener(listener);
  3331. }
  3332. }
  3333. };
  3334. skeleton.setInterruptListener = function (listener) {
  3335. this._interruptListener = listener;
  3336. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3337. this._nativeSkeleton.setInterruptListener(listener);
  3338. }
  3339. };
  3340. skeleton.setEndListener = function (listener) {
  3341. this._endListener = listener;
  3342. if (this._nativeSkeleton) {
  3343. if (this.isAnimationCached()) {
  3344. this._nativeSkeleton.setEndListener(function (animationName) {
  3345. const self = this._comp;
  3346. self._endEntry.animation.name = animationName;
  3347. self._endListener && self._endListener(self._endEntry);
  3348. });
  3349. } else {
  3350. this._nativeSkeleton.setEndListener(listener);
  3351. }
  3352. }
  3353. };
  3354. skeleton.setDisposeListener = function (listener) {
  3355. this._disposeListener = listener;
  3356. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3357. this._nativeSkeleton.setDisposeListener(listener);
  3358. }
  3359. };
  3360. skeleton.setCompleteListener = function (listener) {
  3361. this._completeListener = listener;
  3362. if (this._nativeSkeleton) {
  3363. if (this.isAnimationCached()) {
  3364. this._nativeSkeleton.setCompleteListener(function (animationName) {
  3365. const self = this._comp;
  3366. self._endEntry.animation.name = animationName;
  3367. self._completeListener && self._completeListener(self._endEntry);
  3368. });
  3369. } else {
  3370. this._nativeSkeleton.setCompleteListener(listener);
  3371. }
  3372. }
  3373. };
  3374. skeleton.setEventListener = function (listener) {
  3375. this._eventListener = listener;
  3376. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3377. this._nativeSkeleton.setEventListener(listener);
  3378. }
  3379. };
  3380. skeleton.setTrackStartListener = function (entry, listener) {
  3381. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3382. this._nativeSkeleton.setTrackStartListener(entry, listener);
  3383. }
  3384. };
  3385. skeleton.setTrackInterruptListener = function (entry, listener) {
  3386. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3387. this._nativeSkeleton.setTrackInterruptListener(entry, listener);
  3388. }
  3389. };
  3390. skeleton.setTrackEndListener = function (entry, listener) {
  3391. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3392. this._nativeSkeleton.setTrackEndListener(entry, listener);
  3393. }
  3394. };
  3395. skeleton.setTrackDisposeListener = function (entry, listener) {
  3396. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3397. this._nativeSkeleton.setTrackDisposeListener(entry, listener);
  3398. }
  3399. };
  3400. skeleton.setTrackCompleteListener = function (entry, listener) {
  3401. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3402. this._nativeSkeleton.setTrackCompleteListener(entry, listener);
  3403. }
  3404. };
  3405. skeleton.setTrackEventListener = function (entry, listener) {
  3406. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3407. this._nativeSkeleton.setTrackEventListener(entry, listener);
  3408. }
  3409. };
  3410. skeleton.getState = function () {
  3411. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3412. return this._nativeSkeleton.getState();
  3413. }
  3414. return null;
  3415. };
  3416. skeleton._ensureListener = function () {
  3417. cc.warn('Spine Skeleton _ensureListener not need in native');
  3418. };
  3419. skeleton._updateSkeletonData = function () {
  3420. if (this.skeletonData) {
  3421. this.skeletonData.init();
  3422. this.setSkeletonData(this.skeletonData);
  3423. this._indexBoneSockets();
  3424. this.attachUtil.init(this);
  3425. this._preCacheMode = this._cacheMode;
  3426. this.defaultSkin && this._nativeSkeleton.setSkin(this.defaultSkin);
  3427. this.animation = this.defaultAnimation;
  3428. } else if (this._nativeSkeleton) {
  3429. this._nativeSkeleton.stopSchedule();
  3430. this._nativeSkeleton._comp = null;
  3431. this._nativeSkeleton = null;
  3432. }
  3433. this._needUpdateSkeltonData = false;
  3434. };
  3435. const _onDestroy = skeleton.onDestroy;
  3436. skeleton.onDestroy = function () {
  3437. _onDestroy.call(this);
  3438. if (this._nativeSkeleton) {
  3439. this._nativeSkeleton.stopSchedule();
  3440. this._nativeSkeleton._comp = null;
  3441. this._nativeSkeleton = null;
  3442. }
  3443. this._stateData = null;
  3444. };
  3445. const _tempAttachMat4 = cc.mat4();
  3446. skeleton._render = function () {
  3447. const nativeSkeleton = this._nativeSkeleton;
  3448. if (!nativeSkeleton) return;
  3449. const socketNodes = this.socketNodes;
  3450. if (socketNodes.size > 0) {
  3451. const sharedBufferOffset = this._sharedBufferOffset;
  3452. if (!sharedBufferOffset) return;
  3453. const attachInfoMgr = middleware.attachInfoMgr;
  3454. const attachInfo = attachInfoMgr.attachInfo;
  3455. const attachInfoOffset = sharedBufferOffset[0]; // reset attach info offset
  3456. sharedBufferOffset[0] = 0;
  3457. for (const boneIdx of socketNodes.keys()) {
  3458. const boneNode = socketNodes.get(boneIdx); // Node has been destroy
  3459. if (!boneNode || !boneNode.isValid) {
  3460. socketNodes.delete(boneIdx);
  3461. continue;
  3462. }
  3463. const tm = _tempAttachMat4;
  3464. const matOffset = attachInfoOffset + boneIdx * 16;
  3465. tm.m00 = attachInfo[matOffset];
  3466. tm.m01 = attachInfo[matOffset + 1];
  3467. tm.m04 = attachInfo[matOffset + 4];
  3468. tm.m05 = attachInfo[matOffset + 5];
  3469. tm.m12 = attachInfo[matOffset + 12];
  3470. tm.m13 = attachInfo[matOffset + 13];
  3471. boneNode.matrix = tm;
  3472. }
  3473. }
  3474. }; //////////////////////////////////////////
  3475. // assembler
  3476. const assembler = cc.internal.SpineAssembler; // eslint-disable-next-line no-unused-vars
  3477. assembler.createData = function (comp) {};
  3478. assembler.updateRenderData = function (comp) {
  3479. comp._render();
  3480. }; // eslint-disable-next-line no-unused-vars
  3481. assembler.fillBuffers = function (comp, renderer) {};
  3482. })();
  3483. },{"./jsb-cache-manager":3}],13:[function(require,module,exports){
  3484. /****************************************************************************
  3485. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  3486. https://www.cocos.com/
  3487. Permission is hereby granted, free of charge, to any person obtaining a copy
  3488. of this software and associated engine source code (the "Software"), a limited,
  3489. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  3490. to use Cocos Creator solely to develop games on your target platforms. You shall
  3491. not use Cocos Creator software for developing other software or tools that's
  3492. used for developing games. You are not granted to publish, distribute,
  3493. sublicense, and/or sell copies of Cocos Creator.
  3494. The software or tools in this License Agreement are licensed, not sold.
  3495. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  3496. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3497. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3498. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3499. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3500. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3501. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  3502. THE SOFTWARE.
  3503. ****************************************************************************/
  3504. 'use strict';
  3505. if (cc.internal.VideoPlayer) {
  3506. const {
  3507. EventType
  3508. } = cc.internal.VideoPlayer;
  3509. let vec3 = cc.Vec3;
  3510. let mat4 = cc.Mat4;
  3511. let _mat4_temp = new mat4();
  3512. let _topLeft = new vec3();
  3513. let _bottomRight = new vec3();
  3514. cc.internal.VideoPlayerImplManager.getImpl = function (componenet) {
  3515. return new VideoPlayerImplJSB(componenet);
  3516. };
  3517. class VideoPlayerImplJSB extends cc.internal.VideoPlayerImpl {
  3518. constructor(componenet) {
  3519. super(componenet);
  3520. this._matViewProj_temp = new mat4();
  3521. }
  3522. syncClip(clip) {
  3523. this.removeVideoPlayer();
  3524. if (!clip) {
  3525. return;
  3526. }
  3527. this.createVideoPlayer(clip._nativeAsset);
  3528. }
  3529. syncURL(url) {
  3530. this.removeVideoPlayer();
  3531. if (!url) {
  3532. return;
  3533. }
  3534. this.createVideoPlayer(url);
  3535. }
  3536. onCanplay() {
  3537. if (this._loaded) {
  3538. return;
  3539. }
  3540. this._loaded = true;
  3541. this.video.setVisible(this._visible);
  3542. this.dispatchEvent(EventType.READY_TO_PLAY);
  3543. this.delayedPlay();
  3544. }
  3545. _bindEvent() {
  3546. this.video.addEventListener('loadedmetadata', this.onLoadedMetadata.bind(this));
  3547. this.video.addEventListener('suspend', this.onCanPlay.bind(this));
  3548. this.video.addEventListener('play', this.onPlay.bind(this));
  3549. this.video.addEventListener('pause', this.onPause.bind(this));
  3550. this.video.addEventListener('stoped', this.onStoped.bind(this));
  3551. this.video.addEventListener('click', this.onClick.bind(this));
  3552. this.video.addEventListener('ended', this.onEnded.bind(this));
  3553. }
  3554. onLoadedMetadata() {
  3555. this._loadedMeta = true;
  3556. this._forceUpdate = true;
  3557. if (this._visible) {
  3558. this.enable();
  3559. } else {
  3560. this.disable();
  3561. }
  3562. this.dispatchEvent(EventType.META_LOADED);
  3563. this.delayedFullScreen();
  3564. this.delayedPlay();
  3565. }
  3566. createVideoPlayer(url) {
  3567. this._video = new jsb.VideoPlayer();
  3568. this._bindEvent();
  3569. this._video.setVisible(this._visible);
  3570. this._video.setURL(url);
  3571. this._forceUpdate = true;
  3572. }
  3573. removeVideoPlayer() {
  3574. let video = this.video;
  3575. if (video) {
  3576. video.stop();
  3577. video.setVisible(false);
  3578. video.destroy();
  3579. this._playing = false;
  3580. this._loaded = false;
  3581. this._loadedMeta = false;
  3582. this._ignorePause = false;
  3583. this._cachedCurrentTime = 0;
  3584. this._video = null;
  3585. }
  3586. }
  3587. getDuration() {
  3588. if (!this.video) {
  3589. return -1;
  3590. }
  3591. return this.video.duration();
  3592. }
  3593. syncPlaybackRate() {
  3594. cc.warn('The platform does not support');
  3595. }
  3596. syncVolume() {
  3597. cc.warn('The platform does not support');
  3598. }
  3599. syncMute() {
  3600. cc.warn('The platform does not support');
  3601. }
  3602. syncLoop() {
  3603. cc.warn('The platform does not support');
  3604. }
  3605. syncStayOnBottom() {
  3606. cc.warn('The platform does not support');
  3607. }
  3608. getCurrentTime() {
  3609. if (this.video) {
  3610. this._cachedCurrentTime = this.video.currentTime();
  3611. return this._cachedCurrentTime;
  3612. }
  3613. return -1;
  3614. }
  3615. seekTo(val) {
  3616. let video = this._video;
  3617. if (!video) return;
  3618. video.seekTo(val);
  3619. this._cachedCurrentTime = val;
  3620. }
  3621. disable(noPause) {
  3622. if (this.video) {
  3623. if (!noPause) {
  3624. this.video.pause();
  3625. }
  3626. this.video.setVisible(false);
  3627. this._visible = false;
  3628. }
  3629. }
  3630. enable() {
  3631. if (this.video) {
  3632. this.video.setVisible(true);
  3633. this._visible = true;
  3634. }
  3635. }
  3636. canPlay() {
  3637. this.video.play();
  3638. this.syncCurrentTime();
  3639. }
  3640. resume() {
  3641. if (this.video) {
  3642. this.video.resume();
  3643. this.syncCurrentTime();
  3644. this._playing = true;
  3645. }
  3646. }
  3647. pause() {
  3648. if (this.video) {
  3649. this._cachedCurrentTime = this.video.currentTime();
  3650. this.video.pause();
  3651. }
  3652. }
  3653. stop() {
  3654. if (this.video) {
  3655. this._ignorePause = true;
  3656. this.video.seekTo(0);
  3657. this._cachedCurrentTime = 0;
  3658. this.video.stop();
  3659. }
  3660. }
  3661. canFullScreen(enabled) {
  3662. if (this.video) {
  3663. this.video.setFullScreenEnabled(enabled);
  3664. }
  3665. }
  3666. syncKeepAspectRatio(enabled) {
  3667. if (this.video) {
  3668. this.video.setKeepAspectRatioEnabled(enabled);
  3669. }
  3670. }
  3671. syncMatrix() {
  3672. if (!this._video || !this._component || !this._uiTrans) return;
  3673. const camera = this.UICamera;
  3674. if (!camera) {
  3675. return;
  3676. }
  3677. this._component.node.getWorldMatrix(_mat4_temp);
  3678. const {
  3679. width,
  3680. height
  3681. } = this._uiTrans.contentSize;
  3682. if (!this._forceUpdate && camera.matViewProj.equals(this._matViewProj_temp) && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === width && this._h === height) {
  3683. return;
  3684. }
  3685. this._matViewProj_temp.set(camera.matViewProj); // update matrix cache
  3686. this._m00 = _mat4_temp.m00;
  3687. this._m01 = _mat4_temp.m01;
  3688. this._m04 = _mat4_temp.m04;
  3689. this._m05 = _mat4_temp.m05;
  3690. this._m12 = _mat4_temp.m12;
  3691. this._m13 = _mat4_temp.m13;
  3692. this._w = width;
  3693. this._h = height;
  3694. let canvas_width = cc.game.canvas.width;
  3695. let canvas_height = cc.game.canvas.height;
  3696. let ap = this._uiTrans.anchorPoint; // Vectors in node space
  3697. vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
  3698. vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0); // Convert to world space
  3699. vec3.transformMat4(_topLeft, _topLeft, _mat4_temp);
  3700. vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp); // need update camera data
  3701. camera.update(); // Convert to Screen space
  3702. camera.worldToScreen(_topLeft, _topLeft);
  3703. camera.worldToScreen(_bottomRight, _bottomRight);
  3704. let finalWidth = _bottomRight.x - _topLeft.x;
  3705. let finalHeight = _topLeft.y - _bottomRight.y;
  3706. this._video.setFrame(_topLeft.x, canvas_height - _topLeft.y, finalWidth, finalHeight);
  3707. this._forceUpdate = false;
  3708. }
  3709. }
  3710. }
  3711. },{}],14:[function(require,module,exports){
  3712. /****************************************************************************
  3713. Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
  3714. https://www.cocos.com/
  3715. Permission is hereby granted, free of charge, to any person obtaining a copy
  3716. of this software and associated engine source code (the "Software"), a limited,
  3717. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  3718. to use Cocos Creator solely to develop games on your target platforms. You shall
  3719. not use Cocos Creator software for developing other software or tools that's
  3720. used for developing games. You are not granted to publish, distribute,
  3721. sublicense, and/or sell copies of Cocos Creator.
  3722. The software or tools in this License Agreement are licensed, not sold.
  3723. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  3724. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3725. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3726. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3727. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3728. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3729. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  3730. THE SOFTWARE.
  3731. ****************************************************************************/
  3732. 'use strict';
  3733. if (cc.internal.WebView) {
  3734. const {
  3735. EventType
  3736. } = cc.internal.WebView;
  3737. let vec3 = cc.Vec3;
  3738. let mat4 = cc.Mat4;
  3739. let _mat4_temp = new mat4();
  3740. let _topLeft = new vec3();
  3741. let _bottomRight = new vec3();
  3742. cc.internal.WebViewImplManager.getImpl = function (componenet) {
  3743. return new WebViewImplJSB(componenet);
  3744. };
  3745. class WebViewImplJSB extends cc.internal.WebViewImpl {
  3746. constructor(componenet) {
  3747. super(componenet);
  3748. this.jsCallback = null;
  3749. this.interfaceSchema = null;
  3750. this._matViewProj_temp = new mat4();
  3751. }
  3752. _bindEvent() {
  3753. let onLoaded = () => {
  3754. this._forceUpdate = true;
  3755. this.dispatchEvent(EventType.LOADED);
  3756. };
  3757. let onError = () => {
  3758. this.dispatchEvent(EventType.ERROR);
  3759. };
  3760. this.webview.setOnDidFinishLoading(onLoaded);
  3761. this.webview.setOnDidFailLoading(onError);
  3762. this.jsCallback && this.setOnJSCallback(this.jsCallback);
  3763. this.interfaceSchema && this.setJavascriptInterfaceScheme(this.interfaceSchema); // remove obj
  3764. this.jsCallback = null;
  3765. this.interfaceSchema = null;
  3766. }
  3767. createWebView() {
  3768. if (!jsb.WebView) {
  3769. console.warn('jsb.WebView is null');
  3770. return;
  3771. }
  3772. this._webview = jsb.WebView.create();
  3773. this._bindEvent();
  3774. }
  3775. removeWebView() {
  3776. let webview = this.webview;
  3777. if (webview) {
  3778. this.webview.destroy();
  3779. this.reset();
  3780. }
  3781. }
  3782. disable() {
  3783. if (this.webview) {
  3784. this.webview.setVisible(false);
  3785. }
  3786. }
  3787. enable() {
  3788. if (this.webview) {
  3789. this.webview.setVisible(true);
  3790. }
  3791. }
  3792. setOnJSCallback(callback) {
  3793. let webview = this.webview;
  3794. if (webview) {
  3795. webview.setOnJSCallback(callback);
  3796. } else {
  3797. this.jsCallback = callback;
  3798. }
  3799. }
  3800. setJavascriptInterfaceScheme(scheme) {
  3801. let webview = this.webview;
  3802. if (webview) {
  3803. webview.setJavascriptInterfaceScheme(scheme);
  3804. } else {
  3805. this.interfaceSchema = scheme;
  3806. }
  3807. }
  3808. loadURL(url) {
  3809. let webview = this.webview;
  3810. if (webview) {
  3811. webview.src = url;
  3812. webview.loadURL(url);
  3813. this.dispatchEvent(EventType.LOADING);
  3814. }
  3815. }
  3816. evaluateJS(str) {
  3817. let webview = this.webview;
  3818. if (webview) {
  3819. return webview.evaluateJS(str);
  3820. }
  3821. }
  3822. syncMatrix() {
  3823. if (!this._webview || !this._component || !this._uiTrans) return;
  3824. const camera = this.UICamera;
  3825. if (!camera) {
  3826. return;
  3827. }
  3828. this._component.node.getWorldMatrix(_mat4_temp);
  3829. const {
  3830. width,
  3831. height
  3832. } = this._uiTrans.contentSize;
  3833. if (!this._forceUpdate && camera.matViewProj.equals(this._matViewProj_temp) && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === width && this._h === height) {
  3834. return;
  3835. }
  3836. this._matViewProj_temp.set(camera.matViewProj); // update matrix cache
  3837. this._m00 = _mat4_temp.m00;
  3838. this._m01 = _mat4_temp.m01;
  3839. this._m04 = _mat4_temp.m04;
  3840. this._m05 = _mat4_temp.m05;
  3841. this._m12 = _mat4_temp.m12;
  3842. this._m13 = _mat4_temp.m13;
  3843. this._w = width;
  3844. this._h = height;
  3845. let canvas_width = cc.game.canvas.width;
  3846. let canvas_height = cc.game.canvas.height;
  3847. let ap = this._uiTrans.anchorPoint; // Vectors in node space
  3848. vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
  3849. vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0); // Convert to world space
  3850. vec3.transformMat4(_topLeft, _topLeft, _mat4_temp);
  3851. vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp); // need update camera data
  3852. camera.update(); // Convert to Screen space
  3853. camera.worldToScreen(_topLeft, _topLeft);
  3854. camera.worldToScreen(_bottomRight, _bottomRight);
  3855. let finalWidth = _bottomRight.x - _topLeft.x;
  3856. let finalHeight = _topLeft.y - _bottomRight.y;
  3857. this._webview.setFrame(_topLeft.x, canvas_height - _topLeft.y, finalWidth, finalHeight);
  3858. this._forceUpdate = false;
  3859. }
  3860. }
  3861. }
  3862. },{}]},{},[1]);