123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863 |
- (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){
- "use strict";
- /****************************************************************************
- Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- require('./jsb-assets-manager.js');
- require('./jsb-game.js');
- require('./jsb-gfx.js');
- require('./jsb-loader.js');
- require('./jsb-videoplayer.js');
- require('./jsb-webview.js');
- require('./jsb-editbox.js');
- require('./jsb-editor-support.js');
- require('./jsb-spine-skeleton.js');
- require('./jsb-dragonbones.js');
- if (cc.physics && cc.physics.PhysicsSystem.PHYSICS_PHYSX) {
- require('./jsb-physics.js');
- }
- },{"./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){
- "use strict";
- /*
- * Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
- if (jsb.AssetsManager) {
- jsb.AssetsManager.State = {
- UNINITED: 0,
- UNCHECKED: 1,
- PREDOWNLOAD_VERSION: 2,
- DOWNLOADING_VERSION: 3,
- VERSION_LOADED: 4,
- PREDOWNLOAD_MANIFEST: 5,
- DOWNLOADING_MANIFEST: 6,
- MANIFEST_LOADED: 7,
- NEED_UPDATE: 8,
- READY_TO_UPDATE: 9,
- UPDATING: 10,
- UNZIPPING: 11,
- UP_TO_DATE: 12,
- FAIL_TO_UPDATE: 13
- };
- jsb.Manifest.DownloadState = {
- UNSTARTED: 0,
- DOWNLOADING: 1,
- SUCCESSED: 2,
- UNMARKED: 3
- };
- jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0;
- jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1;
- jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2;
- jsb.EventAssetsManager.NEW_VERSION_FOUND = 3;
- jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4;
- jsb.EventAssetsManager.UPDATE_PROGRESSION = 5;
- jsb.EventAssetsManager.ASSET_UPDATED = 6;
- jsb.EventAssetsManager.ERROR_UPDATING = 7;
- jsb.EventAssetsManager.UPDATE_FINISHED = 8;
- jsb.EventAssetsManager.UPDATE_FAILED = 9;
- jsb.EventAssetsManager.ERROR_DECOMPRESS = 10;
- }
- },{}],3:[function(require,module,exports){
- "use strict";
- /****************************************************************************
- Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of cache-manager software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in cache-manager License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- const {
- getUserDataPath,
- readJsonSync,
- makeDirSync,
- writeFileSync,
- deleteFile,
- rmdirSync
- } = require('./jsb-fs-utils');
- var writeCacheFileList = null;
- var cleaning = false;
- const REGEX = /^\w+:\/\/.*/;
- var cacheManager = {
- cacheDir: 'gamecaches',
- cachedFileName: 'cacheList.json',
- deleteInterval: 500,
- writeFileInterval: 2000,
- cachedFiles: null,
- version: '1.1',
- getCache(url) {
- this.updateLastTime(url);
- return this.cachedFiles.has(url) ? `${this.cacheDir}/${this.cachedFiles.get(url).url}` : '';
- },
- getTemp(url) {
- return '';
- },
- init() {
- this.cacheDir = getUserDataPath() + '/' + this.cacheDir;
- var cacheFilePath = this.cacheDir + '/' + this.cachedFileName;
- var result = readJsonSync(cacheFilePath);
- if (result instanceof Error || !result.version || result.version !== this.version) {
- if (!(result instanceof Error)) rmdirSync(this.cacheDir, true);
- this.cachedFiles = new cc.AssetManager.Cache();
- makeDirSync(this.cacheDir, true);
- writeFileSync(cacheFilePath, JSON.stringify({
- files: this.cachedFiles._map,
- version: this.version
- }), 'utf8');
- } else {
- this.cachedFiles = new cc.AssetManager.Cache(result.files);
- }
- },
- updateLastTime(url) {
- if (this.cachedFiles.has(url)) {
- var cache = this.cachedFiles.get(url);
- cache.lastTime = Date.now();
- }
- },
- _write() {
- writeCacheFileList = null;
- writeFileSync(this.cacheDir + '/' + this.cachedFileName, JSON.stringify({
- files: this.cachedFiles._map,
- version: this.version
- }), 'utf8');
- },
- writeCacheFile() {
- if (!writeCacheFileList) {
- writeCacheFileList = setTimeout(this._write.bind(this), this.writeFileInterval);
- }
- },
- cacheFile(id, url, cacheBundleRoot) {
- this.cachedFiles.add(id, {
- bundle: cacheBundleRoot,
- url,
- lastTime: Date.now()
- });
- this.writeCacheFile();
- },
- clearCache() {
- rmdirSync(this.cacheDir, true);
- this.cachedFiles = new cc.AssetManager.Cache();
- makeDirSync(this.cacheDir, true);
- clearTimeout(writeCacheFileList);
- this._write();
- cc.assetManager.bundles.forEach(bundle => {
- if (REGEX.test(bundle.base)) this.makeBundleFolder(bundle.name);
- });
- },
- clearLRU() {
- if (cleaning) return;
- cleaning = true;
- var caches = [];
- var self = this;
- this.cachedFiles.forEach((val, key) => {
- if (val.bundle === 'internal') return;
- caches.push({
- originUrl: key,
- url: this.getCache(key),
- lastTime: val.lastTime
- });
- });
- caches.sort(function (a, b) {
- return a.lastTime - b.lastTime;
- });
- caches.length = Math.floor(caches.length / 3);
- if (caches.length === 0) return;
- for (var i = 0, l = caches.length; i < l; i++) {
- this.cachedFiles.remove(caches[i].originUrl);
- }
- clearTimeout(writeCacheFileList);
- this._write();
- function deferredDelete() {
- var item = caches.pop();
- deleteFile(item.url);
- if (caches.length > 0) {
- setTimeout(deferredDelete, self.deleteInterval);
- } else {
- cleaning = false;
- }
- }
- setTimeout(deferredDelete, self.deleteInterval);
- },
- removeCache(url) {
- if (this.cachedFiles.has(url)) {
- var path = this.getCache(url);
- this.cachedFiles.remove(url);
- clearTimeout(writeCacheFileList);
- this._write();
- deleteFile(path);
- }
- },
- makeBundleFolder(bundleName) {
- makeDirSync(this.cacheDir + '/' + bundleName, true);
- }
- };
- cc.assetManager.cacheManager = module.exports = cacheManager;
- },{"./jsb-fs-utils":7}],4:[function(require,module,exports){
- "use strict";
- /****************************************************************************
- Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
- http://www.cocos.com
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- const cacheManager = require('./jsb-cache-manager'); // @ts-expect-error jsb polyfills
- (function () {
- if (window.dragonBones === undefined || window.middleware === undefined) return;
- const ArmatureDisplayComponent = cc.internal.ArmatureDisplay;
- if (ArmatureDisplayComponent === undefined) return;
- const dragonBones = window.dragonBones;
- const middleware = window.middleware; // dragonbones global time scale.
- Object.defineProperty(dragonBones, 'timeScale', {
- get() {
- return this._timeScale;
- },
- set(value) {
- this._timeScale = value;
- const factory = this.CCFactory.getInstance();
- factory.setTimeScale(value);
- },
- configurable: true
- });
- middleware.generateGetSet(dragonBones);
- const _slotColor = cc.color(0, 0, 255, 255);
- const _boneColor = cc.color(255, 0, 0, 255);
- const _originColor = cc.color(0, 255, 0, 255); ////////////////////////////////////////////////////////////
- // override dragonBones library by native dragonBones
- ////////////////////////////////////////////////////////////
- //--------------------
- // adapt event name
- //--------------------
- dragonBones.EventObject.START = 'start';
- dragonBones.EventObject.LOOP_COMPLETE = 'loopComplete';
- dragonBones.EventObject.COMPLETE = 'complete';
- dragonBones.EventObject.FADE_IN = 'fadeIn';
- dragonBones.EventObject.FADE_IN_COMPLETE = 'fadeInComplete';
- dragonBones.EventObject.FADE_OUT = 'fadeOut';
- dragonBones.EventObject.FADE_OUT_COMPLETE = 'fadeOutComplete';
- dragonBones.EventObject.FRAME_EVENT = 'frameEvent';
- dragonBones.EventObject.SOUND_EVENT = 'soundEvent';
- dragonBones.DragonBones = {
- ANGLE_TO_RADIAN: Math.PI / 180,
- RADIAN_TO_ANGLE: 180 / Math.PI
- }; //-------------------
- // native factory
- //-------------------
- const factoryProto = dragonBones.CCFactory.prototype;
- factoryProto.createArmatureNode = function (comp, armatureName, node) {
- node = node || new cc.Node();
- let display = node.getComponent(ArmatureDisplayComponent);
- if (!display) {
- display = node.addComponent(ArmatureDisplayComponent);
- }
- node.name = armatureName;
- display._armatureName = armatureName;
- display._dragonAsset = comp.dragonAsset;
- display._dragonAtlasAsset = comp.dragonAtlasAsset;
- display._init();
- return display;
- };
- const _replaceSkin = factoryProto.replaceSkin;
- factoryProto.replaceSkin = function (armatrue, skinData, isOverride, exclude) {
- if (isOverride === undefined) isOverride = false;
- exclude = exclude || [];
- _replaceSkin.call(this, armatrue, skinData, isOverride, exclude);
- };
- const _changeSkin = factoryProto.changeSkin;
- factoryProto.changeSkin = function (armatrue, skinData, exclude) {
- _changeSkin.call(this, armatrue, skinData, exclude);
- };
- dragonBones.CCFactory.getInstance = function () {
- return dragonBones.CCFactory.getFactory();
- }; //-------------------
- // native animation state
- //-------------------
- const animationStateProto = dragonBones.AnimationState.prototype;
- const _isPlaying = animationStateProto.isPlaying;
- Object.defineProperty(animationStateProto, 'isPlaying', {
- get() {
- return _isPlaying.call(this);
- }
- }); //-------------------
- // native armature
- //-------------------
- const armatureProto = dragonBones.Armature.prototype;
- armatureProto.addEventListener = function (eventType, listener, target) {
- this.__persistentDisplay__ = this.getDisplay();
- this.__persistentDisplay__.on(eventType, listener, target);
- };
- armatureProto.removeEventListener = function (eventType, listener, target) {
- this.__persistentDisplay__ = this.getDisplay();
- this.__persistentDisplay__.off(eventType, listener, target);
- }; //--------------------------
- // native CCArmatureDisplay
- //--------------------------
- const nativeArmatureDisplayProto = dragonBones.CCArmatureDisplay.prototype;
- Object.defineProperty(nativeArmatureDisplayProto, 'node', {
- get() {
- return this;
- }
- });
- nativeArmatureDisplayProto.getRootNode = function () {
- const rootDisplay = this.getRootDisplay();
- return rootDisplay && rootDisplay._ccNode;
- };
- nativeArmatureDisplayProto.convertToWorldSpace = function (point) {
- let newPos = this.convertToRootSpace(point.x, point.y);
- newPos = cc.v3(newPos.x, newPos.y, 0);
- const ccNode = this.getRootNode();
- if (!ccNode) return newPos;
- const finalPos = ccNode._uiProps.uiTransformComp.convertToWorldSpaceAR(newPos);
- return finalPos;
- };
- nativeArmatureDisplayProto.initEvent = function () {
- if (this._eventTarget) {
- return;
- }
- this._eventTarget = new cc.EventTarget();
- this.setDBEventCallback(function (eventObject) {
- this._eventTarget.emit(eventObject.type, eventObject);
- });
- };
- nativeArmatureDisplayProto.on = function (type, listener, target) {
- this.initEvent();
- this._eventTarget.on(type, listener, target);
- this.addDBEventListener(type, listener);
- };
- nativeArmatureDisplayProto.off = function (type, listener, target) {
- this.initEvent();
- this._eventTarget.off(type, listener, target);
- this.removeDBEventListener(type, listener);
- };
- nativeArmatureDisplayProto.once = function (type, listener, target) {
- this.initEvent();
- this._eventTarget.once(type, listener, target);
- this.addDBEventListener(type, listener);
- }; ////////////////////////////////////////////////////////////
- // override DragonBonesAtlasAsset
- ////////////////////////////////////////////////////////////
- const dbAtlas = cc.internal.DragonBonesAtlasAsset.prototype;
- let _gTextureIdx = 1;
- const _textureKeyMap = {};
- const _textureMap = new WeakMap();
- const _textureIdx2Name = {};
- dbAtlas.removeRecordTexture = function (texture) {
- if (!texture) return;
- delete _textureIdx2Name[texture.image.url];
- const index = texture.__textureIndex__;
- if (index) {
- const texKey = _textureKeyMap[index];
- if (texKey && _textureMap.has(texKey)) {
- _textureMap.delete(texKey);
- delete _textureKeyMap[index];
- }
- }
- };
- dbAtlas.recordTexture = function () {
- if (this._texture && this._oldTexture !== this._texture) {
- this.removeRecordTexture(this._oldTexture);
- const texKey = _textureKeyMap[_gTextureIdx] = {
- key: _gTextureIdx
- };
- _textureMap.set(texKey, this._texture);
- this._oldTexture = this._texture;
- this._texture.__textureIndex__ = _gTextureIdx;
- _gTextureIdx++;
- }
- };
- dbAtlas.getTextureByIndex = function (textureIdx) {
- const texKey = _textureKeyMap[textureIdx];
- if (!texKey) return null;
- return _textureMap.get(texKey);
- };
- dbAtlas.updateTextureAtlasData = function (factory) {
- const url = this._texture.image.url;
- const preAtlasInfo = _textureIdx2Name[url];
- let index; // If the texture has store the atlas info before,then get native atlas object,and
- // update script texture map.
- if (preAtlasInfo) {
- index = preAtlasInfo.index;
- this._textureAtlasData = factory.getTextureAtlasDataByIndex(preAtlasInfo.name, index);
- const texKey = _textureKeyMap[preAtlasInfo.index];
- _textureMap.set(texKey, this._texture);
- this._texture.__textureIndex__ = index; // If script has store the atlas info,but native has no atlas object,then
- // still new native texture2d object,but no call recordTexture to increase
- // textureIndex.
- if (this._textureAtlasData) {
- return;
- }
- } else {
- this.recordTexture();
- }
- index = this._texture.__textureIndex__;
- this.jsbTexture = new middleware.Texture2D();
- this.jsbTexture.setRealTextureIndex(index);
- this.jsbTexture.setPixelsWide(this._texture.width);
- this.jsbTexture.setPixelsHigh(this._texture.height);
- this.jsbTexture.setRealTexture(this._texture);
- this._textureAtlasData = factory.parseTextureAtlasData(this.atlasJson, this.jsbTexture, this._uuid);
- _textureIdx2Name[url] = {
- name: this._textureAtlasData.name,
- index
- };
- };
- dbAtlas.init = function (factory) {
- this._factory = factory; // If create by manual, uuid is empty.
- if (!this._uuid) {
- const atlasJsonObj = JSON.parse(this.atlasJson);
- this._uuid = atlasJsonObj.name;
- }
- if (this._textureAtlasData) {
- factory.addTextureAtlasData(this._textureAtlasData, this._uuid);
- } else {
- this.updateTextureAtlasData(factory);
- }
- };
- dbAtlas._clear = function (dontRecordTexture) {
- if (this._factory) {
- this._factory.removeTextureAtlasData(this._uuid, true);
- this._factory.removeDragonBonesDataByUUID(this._uuid, true);
- }
- this._textureAtlasData = null;
- if (!dontRecordTexture) {
- this.recordTexture();
- }
- };
- dbAtlas.destroy = function () {
- this.removeRecordTexture(this._texture);
- this._clear(true);
- cc.Asset.prototype.destroy.call(this);
- }; ////////////////////////////////////////////////////////////
- // override DragonBonesAsset
- ////////////////////////////////////////////////////////////
- const dbAsset = cc.internal.DragonBonesAsset.prototype;
- dbAsset.init = function (factory, atlasUUID) {
- this._factory = factory; // If create by manual, uuid is empty.
- // Only support json format, if remote load dbbin, must set uuid by manual.
- if (!this._uuid && this.dragonBonesJson) {
- const rawData = JSON.parse(this.dragonBonesJson);
- this._uuid = rawData.name;
- }
- const armatureKey = `${this._uuid}#${atlasUUID}`;
- const dragonBonesData = this._factory.getDragonBonesData(armatureKey);
- if (dragonBonesData) return armatureKey;
- let filePath = null;
- if (this.dragonBonesJson) {
- filePath = this.dragonBonesJson;
- } else {
- filePath = cacheManager.getCache(this.nativeUrl) || this.nativeUrl;
- }
- this._factory.parseDragonBonesDataByPath(filePath, armatureKey);
- return armatureKey;
- };
- const armatureCacheMgr = dragonBones.ArmatureCacheMgr.getInstance();
- dragonBones.armatureCacheMgr = armatureCacheMgr;
- dbAsset._clear = function () {
- if (this._factory) {
- this._factory.removeDragonBonesDataByUUID(this._uuid, true);
- }
- armatureCacheMgr.removeArmatureCache(this._uuid);
- }; ////////////////////////////////////////////////////////////
- // override ArmatureDisplay
- ////////////////////////////////////////////////////////////
- const superProto = cc.internal.UIRenderer.prototype;
- const armatureDisplayProto = cc.internal.ArmatureDisplay.prototype;
- const AnimationCacheMode = cc.internal.ArmatureDisplay.AnimationCacheMode;
- const armatureSystem = cc.internal.ArmatureSystem;
- armatureDisplayProto.initFactory = function () {
- this._factory = dragonBones.CCFactory.getFactory();
- };
- Object.defineProperty(armatureDisplayProto, 'armatureName', {
- get() {
- return this._armatureName;
- },
- set(value) {
- this._armatureName = value;
- const animNames = this.getAnimationNames(this._armatureName);
- if (!this.animationName || animNames.indexOf(this.animationName) < 0) {
- this.animationName = '';
- }
- const oldArmature = this._armature;
- if (this._armature) {
- if (!this.isAnimationCached()) {
- this._factory.remove(this._armature);
- }
- this._armature = null;
- }
- this._nativeDisplay = null;
- this._refresh();
- if (oldArmature && oldArmature !== this._armature) {
- oldArmature.dispose();
- }
- if (this._armature && !this.isAnimationCached()) {
- this._factory.add(this._armature);
- }
- },
- visible: false
- });
- Object.defineProperty(armatureDisplayProto, 'premultipliedAlpha', {
- get() {
- if (this._premultipliedAlpha === undefined) {
- return false;
- }
- return this._premultipliedAlpha;
- },
- set(value) {
- this._premultipliedAlpha = value;
- if (this._nativeDisplay) {
- this._nativeDisplay.setOpacityModifyRGB(this._premultipliedAlpha);
- }
- }
- });
- const _initDebugDraw = armatureDisplayProto._initDebugDraw;
- armatureDisplayProto._initDebugDraw = function () {
- _initDebugDraw.call(this);
- if (this._armature && !this.isAnimationCached()) {
- this._nativeDisplay.setDebugBonesEnabled(this.debugBones);
- }
- };
- armatureDisplayProto._buildArmature = function () {
- if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) {
- return;
- }
- if (this._nativeDisplay) {
- this._nativeDisplay.dispose();
- this._nativeDisplay._comp = null;
- this._nativeDisplay = null;
- }
- const atlasUUID = this.dragonAtlasAsset._uuid;
- this._armatureKey = this.dragonAsset.init(this._factory, atlasUUID);
- if (this.isAnimationCached()) {
- const isShare = this._cacheMode === AnimationCacheMode.SHARED_CACHE;
- this._nativeDisplay = new dragonBones.CCArmatureCacheDisplay(this.armatureName, this._armatureKey, atlasUUID, isShare);
- this._armature = this._nativeDisplay.armature();
- } else {
- this._nativeDisplay = this._factory.buildArmatureDisplay(this.armatureName, this._armatureKey, '', atlasUUID);
- if (!this._nativeDisplay) {
- return;
- }
- this._nativeDisplay.setDebugBonesEnabled(this.debugBones);
- this._armature = this._nativeDisplay.armature();
- this._armature.animation.timeScale = this.timeScale;
- this._factory.add(this._armature);
- } // add all event into native display
- const callbackTable = this._eventTarget._callbackTable; // just use to adapt to native api
- const emptyHandle = function () {};
- for (const key in callbackTable) {
- const list = callbackTable[key];
- if (!list || !list.callbackInfos || !list.callbackInfos.length) continue;
- if (this.isAnimationCached()) {
- this._nativeDisplay.addDBEventListener(key);
- } else {
- this._nativeDisplay.addDBEventListener(key, emptyHandle);
- }
- }
- this._preCacheMode = this._cacheMode;
- this._nativeDisplay._ccNode = this.node;
- this._nativeDisplay._comp = this;
- this._nativeDisplay._eventTarget = this._eventTarget;
- this._sharedBufferOffset = this._nativeDisplay.getSharedBufferOffset();
- this._sharedBufferOffset[0] = 0;
- this._useAttach = false;
- this._nativeDisplay.setOpacityModifyRGB(this.premultipliedAlpha);
- const compColor = this.color;
- this._nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
- this._nativeDisplay.setDBEventCallback(function (eventObject) {
- this._eventTarget.emit(eventObject.type, eventObject);
- });
- const materialTemplate = this.getMaterialTemplate();
- this._nativeDisplay.setMaterial(materialTemplate);
- this._nativeDisplay.setRenderEntity(this._renderEntity.nativeObj);
- this.attachUtil.init(this);
- if (this.animationName) {
- this.playAnimation(this.animationName, this.playTimes);
- }
- this.markForUpdateRenderData();
- };
- armatureDisplayProto._updateColor = function () {
- if (this._nativeDisplay) {
- const compColor = this.color;
- this._nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
- }
- };
- armatureDisplayProto.playAnimation = function (animName, playTimes) {
- this.playTimes = playTimes === undefined ? -1 : playTimes;
- this.animationName = animName;
- if (this._nativeDisplay) {
- if (this.isAnimationCached()) {
- return this._nativeDisplay.playAnimation(animName, this.playTimes);
- } else if (this._armature) {
- return this._armature.animation.play(animName, this.playTimes);
- }
- }
- return null;
- };
- armatureDisplayProto.updateAnimationCache = function (animName) {
- if (!this.isAnimationCached()) return;
- if (this._nativeDisplay) {
- if (animName) {
- this._nativeDisplay.updateAnimationCache(animName);
- } else {
- this._nativeDisplay.updateAllAnimationCache();
- }
- }
- };
- armatureDisplayProto.invalidAnimationCache = function () {
- if (!this.isAnimationCached()) return;
- if (this._nativeDisplay) {
- this._nativeDisplay.updateAllAnimationCache();
- }
- };
- const _onEnable = superProto.onEnable;
- armatureDisplayProto.onEnable = function () {
- if (_onEnable) {
- _onEnable.call(this);
- }
- if (this._armature && !this.isAnimationCached()) {
- this._factory.add(this._armature);
- }
- this._flushAssembler();
- armatureSystem.getInstance().add(this);
- middleware.retain();
- };
- const _onDisable = superProto.onDisable;
- armatureDisplayProto.onDisable = function () {
- if (_onDisable) {
- _onDisable.call(this);
- }
- if (this._armature && !this.isAnimationCached()) {
- this._factory.remove(this._armature);
- }
- armatureSystem.getInstance().remove(this);
- middleware.release();
- };
- armatureDisplayProto.once = function (eventType, listener, target) {
- if (this._nativeDisplay) {
- if (this.isAnimationCached()) {
- this._nativeDisplay.addDBEventListener(eventType);
- } else {
- this._nativeDisplay.addDBEventListener(eventType, listener);
- }
- }
- this._eventTarget.once(eventType, listener, target);
- };
- armatureDisplayProto.addEventListener = function (eventType, listener, target) {
- if (this._nativeDisplay) {
- if (this.isAnimationCached()) {
- this._nativeDisplay.addDBEventListener(eventType);
- } else {
- this._nativeDisplay.addDBEventListener(eventType, listener);
- }
- }
- this._eventTarget.on(eventType, listener, target);
- };
- armatureDisplayProto.removeEventListener = function (eventType, listener, target) {
- if (this._nativeDisplay) {
- if (this.isAnimationCached()) {
- this._nativeDisplay.removeDBEventListener(eventType);
- } else {
- this._nativeDisplay.removeDBEventListener(eventType, listener);
- }
- }
- this._eventTarget.off(eventType, listener, target);
- };
- const _onDestroy = armatureDisplayProto.onDestroy;
- armatureDisplayProto.onDestroy = function () {
- _onDestroy.call(this);
- if (this._nativeDisplay) {
- this._nativeDisplay.dispose();
- this._nativeDisplay._comp = null;
- this._nativeDisplay = null;
- }
- };
- armatureDisplayProto.setAnimationCacheMode = function (cacheMode) {
- if (this._preCacheMode !== cacheMode) {
- this._cacheMode = cacheMode;
- this._buildArmature();
- if (this._armature && !this.isAnimationCached()) {
- this._factory.add(this._armature);
- }
- this._updateSocketBindings();
- this.markForUpdateRenderData();
- }
- };
- armatureDisplayProto.updateAnimation = function () {
- const nativeDisplay = this._nativeDisplay;
- if (!nativeDisplay) return;
- const node = this.node;
- if (!node) return;
- if (this.__preColor__ === undefined || !this.color.equals(this.__preColor__)) {
- const compColor = this.color;
- nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
- this.__preColor__ = compColor;
- }
- const socketNodes = this.socketNodes;
- if (!this._useAttach && socketNodes.size > 0) {
- this._useAttach = true;
- nativeDisplay.setAttachEnabled(true);
- }
- this.markForUpdateRenderData();
- if (!this.isAnimationCached() && this._debugDraw && this.debugBones) {
- const nativeDisplay = this._nativeDisplay;
- this._debugData = this._debugData || nativeDisplay.getDebugData();
- if (!this._debugData) return;
- const graphics = this._debugDraw;
- graphics.clear();
- const debugData = this._debugData;
- let debugIdx = 0;
- graphics.lineWidth = 5;
- graphics.strokeColor = _boneColor;
- graphics.fillColor = _slotColor; // Root bone color is same as slot color.
- const debugBonesLen = debugData[debugIdx++];
- for (let i = 0; i < debugBonesLen; i += 4) {
- const bx = debugData[debugIdx++];
- const by = debugData[debugIdx++];
- const x = debugData[debugIdx++];
- const y = debugData[debugIdx++]; // Bone lengths.
- graphics.moveTo(bx, by);
- graphics.lineTo(x, y);
- graphics.stroke(); // Bone origins.
- graphics.circle(bx, by, Math.PI * 2);
- graphics.fill();
- if (i === 0) {
- graphics.fillColor = _originColor;
- }
- }
- }
- };
- const _tempAttachMat4 = cc.mat4();
- armatureDisplayProto._render = function () {
- const nativeDisplay = this._nativeDisplay;
- if (!nativeDisplay) return;
- const sharedBufferOffset = this._sharedBufferOffset;
- if (!sharedBufferOffset) return;
- const sockets = this.sockets;
- if (sockets.length > 0) {
- const attachInfoMgr = middleware.attachInfoMgr;
- const attachInfo = attachInfoMgr.attachInfo;
- const attachInfoOffset = sharedBufferOffset[0]; // reset attach info offset
- sharedBufferOffset[0] = 0;
- const socketNodes = this.socketNodes;
- for (let l = sockets.length - 1; l >= 0; l--) {
- const sock = sockets[l];
- const boneNode = sock.target;
- const boneIdx = sock.boneIndex;
- if (!boneNode) continue; // Node has been destroy
- if (!boneNode.isValid) {
- socketNodes.delete(sock.path);
- sockets.splice(l, 1);
- continue;
- }
- const tm = _tempAttachMat4;
- const matOffset = attachInfoOffset + boneIdx * 16;
- tm.m00 = attachInfo[matOffset];
- tm.m01 = attachInfo[matOffset + 1];
- tm.m04 = attachInfo[matOffset + 4];
- tm.m05 = attachInfo[matOffset + 5];
- tm.m12 = attachInfo[matOffset + 12];
- tm.m13 = attachInfo[matOffset + 13];
- boneNode.matrix = tm;
- }
- }
- };
- armatureDisplayProto._updateBatch = function () {
- if (this.nativeDisplay) {
- this.nativeDisplay.setBatchEnabled(this.enableBatch);
- this.markForUpdateRenderData();
- }
- }; //////////////////////////////////////////
- // assembler
- const assembler = cc.internal.DragonBonesAssembler; // eslint-disable-next-line no-unused-vars
- assembler.createData = function (comp) {};
- assembler.updateRenderData = function (comp) {
- comp._render();
- }; // eslint-disable-next-line no-unused-vars
- assembler.fillBuffers = function (comp, renderer) {};
- })();
- },{"./jsb-cache-manager":3}],5:[function(require,module,exports){
- "use strict";
- /****************************************************************************
- Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- (function () {
- if (!(cc && cc.internal && cc.internal.EditBox)) {
- return;
- }
- const EditBox = cc.internal.EditBox;
- const KeyboardReturnType = EditBox.KeyboardReturnType;
- const InputMode = EditBox.InputMode;
- const InputFlag = EditBox.InputFlag;
- const worldMat = cc.mat4();
- function getInputType(type) {
- switch (type) {
- case InputMode.EMAIL_ADDR:
- return 'email';
- case InputMode.NUMERIC:
- case InputMode.DECIMAL:
- return 'number';
- case InputMode.PHONE_NUMBER:
- return 'phone';
- case InputMode.URL:
- return 'url';
- case InputMode.SINGLE_LINE:
- case InputMode.ANY:
- default:
- return 'text';
- }
- }
- function getKeyboardReturnType(type) {
- switch (type) {
- case KeyboardReturnType.DEFAULT:
- case KeyboardReturnType.DONE:
- return 'done';
- case KeyboardReturnType.SEND:
- return 'send';
- case KeyboardReturnType.SEARCH:
- return 'search';
- case KeyboardReturnType.GO:
- return 'go';
- case KeyboardReturnType.NEXT:
- return 'next';
- }
- return 'done';
- }
- const BaseClass = EditBox._EditBoxImpl;
- class JsbEditBoxImpl extends BaseClass {
- init(delegate) {
- if (!delegate) {
- cc.error('EditBox init failed');
- return;
- }
- this._delegate = delegate;
- }
- beginEditing() {
- const self = this;
- const delegate = this._delegate;
- const multiline = delegate.inputMode === InputMode.ANY;
- const rect = this._getRect();
- this.setMaxLength(delegate.maxLength);
- let inputTypeString = getInputType(delegate.inputMode);
- if (delegate.inputFlag === InputFlag.PASSWORD) {
- inputTypeString = 'password';
- }
- function onConfirm(res) {
- delegate._editBoxEditingReturn();
- }
- function onInput(res) {
- if (res.value.length > self._maxLength) {
- res.value = res.value.slice(0, self._maxLength);
- }
- if (delegate.string !== res.value) {
- delegate._editBoxTextChanged(res.value);
- }
- }
- function onComplete(res) {
- self.endEditing();
- }
- jsb.inputBox.onInput(onInput);
- jsb.inputBox.onConfirm(onConfirm);
- jsb.inputBox.onComplete(onComplete);
- if (!cc.sys.isMobile) {
- delegate._hideLabels();
- }
- const editLabel = delegate.textLabel;
- jsb.inputBox.show({
- defaultValue: delegate.string,
- maxLength: self._maxLength,
- multiple: multiline,
- confirmHold: false,
- confirmType: getKeyboardReturnType(delegate.returnType),
- inputType: inputTypeString,
- originX: rect.x,
- originY: rect.y,
- width: rect.width,
- height: rect.height,
- isBold: editLabel.isBold,
- isItalic: editLabel.isItalic,
- isUnderline: editLabel.isUnderline,
- underlineColor: 0x00000000
- /* Black */
- ,
- fontSize:
- /**number */
- editLabel.fontSize,
- fontColor:
- /**number */
- editLabel.color.toRGBValue(),
- backColor: 0x00ffffff
- /*White*/
- ,
- backgroundColor: delegate.placeholderLabel.color.toRGBValue(),
- textAlignment:
- /*left = 0, center = 1, right = 2*/
- editLabel.horizontalAlign
- });
- this._editing = true;
- delegate._editBoxEditingDidBegan();
- }
- endEditing() {
- this._editing = false;
- if (!cc.sys.isMobile) {
- this._delegate._showLabels();
- }
- jsb.inputBox.offConfirm();
- jsb.inputBox.offInput();
- jsb.inputBox.offComplete();
- jsb.inputBox.hide();
- this._delegate._editBoxEditingDidEnded();
- }
- setMaxLength(maxLength) {
- if (!isNaN(maxLength)) {
- if (maxLength < 0) {
- //we can't set Number.MAX_VALUE to input's maxLength property
- //so we use a magic number here, it should works at most use cases.
- maxLength = 65535;
- }
- this._maxLength = maxLength;
- }
- }
- _getRect() {
- const node = this._delegate.node;
- let viewScaleX = cc.view._scaleX;
- let viewScaleY = cc.view._scaleY;
- const dpr = jsb.device.getDevicePixelRatio() || 1;
- node.getWorldMatrix(worldMat);
- const transform = node._uiProps.uiTransformComp;
- const vec3 = cc.v3();
- let width = 0;
- let height = 0;
- if (transform) {
- const contentSize = transform.contentSize;
- const anchorPoint = transform.anchorPoint;
- width = contentSize.width;
- height = contentSize.height;
- vec3.x = -anchorPoint.x * width;
- vec3.y = -anchorPoint.y * height;
- }
- cc.Mat4.translate(worldMat, worldMat, vec3);
- viewScaleX /= dpr;
- viewScaleY /= dpr;
- const finalScaleX = worldMat.m00 * viewScaleX;
- const finaleScaleY = worldMat.m05 * viewScaleY;
- const viewportRect = cc.view._viewportRect;
- const offsetX = viewportRect.x / dpr;
- const offsetY = viewportRect.y / dpr;
- return {
- x: worldMat.m12 * viewScaleX + offsetX,
- y: worldMat.m13 * viewScaleY + offsetY,
- width: width * finalScaleX,
- height: height * finaleScaleY
- };
- }
- }
- EditBox._EditBoxImpl = JsbEditBoxImpl;
- })();
- },{}],6:[function(require,module,exports){
- "use strict";
- /****************************************************************************
- Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
- http://www.cocos.com
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- // @ts-expect-error jsb polyfills
- (function () {
- if (!window.middleware) return;
- const middleware = window.middleware;
- const middlewareMgr = middleware.MiddlewareManager.getInstance();
- let reference = 0;
- const director = cc.director;
- const game = cc.game;
- middleware.reset = function () {
- middleware.preRenderComponent = null;
- middleware.preRenderBufferIndex = 0;
- middleware.indicesStart = 0;
- middleware.resetIndicesStart = false;
- };
- middleware.reset();
- middleware.retain = function () {
- reference++;
- };
- middleware.release = function () {
- if (reference === 0) {
- cc.warn('middleware reference error: reference count should be greater than 0');
- return;
- }
- reference--;
- };
- director.on(cc.Director.EVENT_BEFORE_UPDATE, () => {
- if (reference === 0) return;
- middlewareMgr.update(game.deltaTime);
- });
- director.on(cc.Director.EVENT_BEFORE_DRAW, () => {
- if (reference === 0) return;
- middlewareMgr.render(game.deltaTime); // reset render order
- middleware.reset(); //const batcher2D = director.root.batcher2D;
- if (window.dragonBones) {
- const armaSystem = cc.internal.ArmatureSystem.getInstance();
- armaSystem.prepareRenderData();
- }
- if (window.spine) {
- const skeletonSystem = cc.internal.SpineSkeletonSystem.getInstance();
- skeletonSystem.prepareRenderData();
- }
- });
- const attachInfoMgr = middlewareMgr.getAttachInfoMgr();
- attachInfoMgr.attachInfo = attachInfoMgr.getSharedBuffer();
- attachInfoMgr.setResizeCallback(function () {
- this.attachInfo = this.getSharedBuffer();
- });
- middleware.attachInfoMgr = attachInfoMgr; // generate get set function
- middleware.generateGetSet = function (moduleObj) {
- for (const classKey in moduleObj) {
- const classProto = moduleObj[classKey] && moduleObj[classKey].prototype;
- if (!classProto) continue;
- for (const getName in classProto) {
- const getPos = getName.search(/^get/);
- if (getPos === -1) continue;
- let propName = getName.replace(/^get/, '');
- const nameArr = propName.split('');
- const lowerFirst = nameArr[0].toLowerCase();
- const upperFirst = nameArr[0].toUpperCase();
- nameArr.splice(0, 1);
- const left = nameArr.join('');
- propName = lowerFirst + left;
- const setName = `set${upperFirst}${left}`; // eslint-disable-next-line no-prototype-builtins
- if (classProto.hasOwnProperty(propName)) continue;
- const setFunc = classProto[setName];
- const hasSetFunc = typeof setFunc === 'function';
- if (hasSetFunc) {
- Object.defineProperty(classProto, propName, {
- get() {
- return this[getName]();
- },
- set(val) {
- this[setName](val);
- },
- configurable: true
- });
- } else {
- Object.defineProperty(classProto, propName, {
- get() {
- return this[getName]();
- },
- configurable: true
- });
- }
- }
- }
- };
- })();
- },{}],7:[function(require,module,exports){
- "use strict";
- /****************************************************************************
- Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of fsUtils software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in fsUtils License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- const fs = jsb.fileUtils;
- let jsb_downloader = null;
- const downloading = new cc.AssetManager.Cache();
- let tempDir = '';
- jsb.Downloader.prototype._ctor = function () {
- this.__nativeRefs = {};
- };
- var fsUtils = {
- fs,
- initJsbDownloader(jsbDownloaderMaxTasks, jsbDownloaderTimeout) {
- jsb_downloader = new jsb.Downloader({
- countOfMaxProcessingTasks: jsbDownloaderMaxTasks || 32,
- timeoutInSeconds: jsbDownloaderTimeout || 30,
- tempFileNameSuffix: '.tmp'
- });
- tempDir = `${fsUtils.getUserDataPath()}/temp`;
- !fs.isDirectoryExist(tempDir) && fs.createDirectory(tempDir);
- jsb_downloader.onSuccess = task => {
- if (!downloading.has(task.requestURL)) return;
- const {
- onComplete
- } = downloading.remove(task.requestURL);
- onComplete && onComplete(null, task.storagePath);
- };
- jsb_downloader.onError = (task, errorCode, errorCodeInternal, errorStr) => {
- if (!downloading.has(task.requestURL)) return;
- const {
- onComplete
- } = downloading.remove(task.requestURL);
- cc.error(`Download file failed: path: ${task.requestURL} message: ${errorStr}, ${errorCode}`);
- onComplete(new Error(errorStr), null);
- };
- jsb_downloader.onProgress = (task, bytesReceived, totalBytesReceived, totalBytesExpected) => {
- if (!downloading.has(task.requestURL)) return;
- const {
- onProgress
- } = downloading.get(task.requestURL);
- onProgress && onProgress(totalBytesReceived, totalBytesExpected);
- };
- },
- getUserDataPath() {
- return fs.getWritablePath().replace(/[\/\\]*$/, '');
- },
- checkFsValid() {
- if (!fs) {
- cc.warn('can not get the file system!');
- return false;
- }
- return true;
- },
- deleteFile(filePath, onComplete) {
- const result = fs.removeFile(filePath);
- if (result === true) {
- onComplete && onComplete(null);
- } else {
- cc.warn(`Delete file failed: path: ${filePath}`);
- onComplete && onComplete(new Error('delete file failed'));
- }
- },
- downloadFile(remoteUrl, filePath, header, onProgress, onComplete) {
- downloading.add(remoteUrl, {
- onProgress,
- onComplete
- });
- let storagePath = filePath;
- if (!storagePath) storagePath = `${tempDir}/${performance.now()}${cc.path.extname(remoteUrl)}`;
- jsb_downloader.createDownloadTask(remoteUrl, storagePath, header);
- },
- saveFile(srcPath, destPath, onComplete) {
- let err = null;
- const result = fs.writeDataToFile(fs.getDataFromFile(srcPath), destPath);
- fs.removeFile(srcPath);
- if (!result) {
- err = new Error(`Save file failed: path: ${srcPath}`);
- cc.warn(err.message);
- }
- onComplete && onComplete(err);
- },
- copyFile(srcPath, destPath, onComplete) {
- let err = null;
- const result = fs.writeDataToFile(fs.getDataFromFile(srcPath), destPath);
- if (!result) {
- err = new Error(`Copy file failed: path: ${srcPath}`);
- cc.warn(err.message);
- }
- onComplete && onComplete(err);
- },
- writeFile(path, data, encoding, onComplete) {
- let result = null;
- let err = null;
- if (encoding === 'utf-8' || encoding === 'utf8') {
- result = fs.writeStringToFile(data, path);
- } else {
- result = fs.writeDataToFile(data, path);
- }
- if (!result) {
- err = new Error(`Write file failed: path: ${path}`);
- cc.warn(err.message);
- }
- onComplete && onComplete(err);
- },
- writeFileSync(path, data, encoding) {
- let result = null;
- if (encoding === 'utf-8' || encoding === 'utf8') {
- result = fs.writeStringToFile(data, path);
- } else {
- result = fs.writeDataToFile(data, path);
- }
- if (!result) {
- cc.warn(`Write file failed: path: ${path}`);
- return new Error(`Write file failed: path: ${path}`);
- }
- },
- readFile(filePath, encoding, onComplete) {
- let content = null;
- let err = null;
- if (encoding === 'utf-8' || encoding === 'utf8') {
- content = fs.getStringFromFile(filePath);
- } else {
- content = fs.getDataFromFile(filePath);
- }
- if (!content) {
- err = new Error(`Read file failed: path: ${filePath}`);
- cc.warn(err.message);
- }
- onComplete && onComplete(err, content);
- },
- readDir(filePath, onComplete) {
- let files = null;
- let err = null;
- try {
- files = fs.listFiles(filePath);
- } catch (e) {
- cc.warn(`Read dir failed: path: ${filePath} message: ${e.message}`);
- err = new Error(e.message);
- }
- onComplete && onComplete(err, files);
- },
- readText(filePath, onComplete) {
- fsUtils.readFile(filePath, 'utf8', onComplete);
- },
- readArrayBuffer(filePath, onComplete) {
- fsUtils.readFile(filePath, '', onComplete);
- },
- readJson(filePath, onComplete) {
- fsUtils.readFile(filePath, 'utf8', (err, text) => {
- let out = null;
- if (!err) {
- try {
- out = JSON.parse(text);
- } catch (e) {
- cc.warn(`Read json failed: path: ${filePath} message: ${e.message}`);
- err = new Error(e.message);
- }
- }
- onComplete && onComplete(err, out);
- });
- },
- readJsonSync(path) {
- try {
- const str = fs.getStringFromFile(path);
- return JSON.parse(str);
- } catch (e) {
- cc.warn(`Read json failed: path: ${path} message: ${e.message}`);
- return new Error(e.message);
- }
- },
- makeDirSync(path, recursive) {
- const result = fs.createDirectory(path);
- if (!result) {
- cc.warn(`Make directory failed: path: ${path}`);
- return new Error(`Make directory failed: path: ${path}`);
- }
- },
- rmdirSync(dirPath, recursive) {
- const result = fs.removeDirectory(dirPath);
- if (!result) {
- cc.warn(`rm directory failed: path: ${dirPath}`);
- return new Error(`rm directory failed: path: ${dirPath}`);
- }
- },
- exists(filePath, onComplete) {
- const result = fs.isFileExist(filePath);
- onComplete && onComplete(result);
- },
- loadSubpackage(name, onProgress, onComplete) {
- throw new Error('not implement');
- }
- };
- window.fsUtils = module.exports = fsUtils;
- },{}],8:[function(require,module,exports){
- "use strict";
- /****************************************************************************
- Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- cc.game.restart = function () {
- // Need to clear scene, or native object destructor won't be invoke.
- cc.director.getScene().destroy();
- cc.Object._deferredDestroy();
- __restartVM();
- };
- jsb.onError(function (location, message, stack) {
- console.error(location, message, stack);
- });
- jsb.onMemoryWarning = function () {
- cc.game.emit(cc.Game.EVENT_LOW_MEMORY);
- };
- },{}],9:[function(require,module,exports){
- "use strict";
- /****************************************************************************
- Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- /* global gfx */
- const deviceProto = gfx.Device.prototype;
- const swapchainProto = gfx.Swapchain.prototype;
- const bufferProto = gfx.Buffer.prototype;
- const textureProto = gfx.Texture.prototype;
- const descriptorSetProto = gfx.DescriptorSet.prototype; ///////////////////////////// handle different paradigms /////////////////////////////
- const oldCopyTexImagesToTextureFunc = deviceProto.copyTexImagesToTexture;
- deviceProto.copyTexImagesToTexture = function (texImages, texture, regions) {
- const images = [];
- if (texImages) {
- for (let i = 0; i < texImages.length; ++i) {
- const texImage = texImages[i];
- if (texImage instanceof HTMLCanvasElement) {
- // Refer to HTMLCanvasElement and ImageData implementation
- images.push(texImage._data.data);
- } else if (texImage instanceof HTMLImageElement) {
- // Refer to HTMLImageElement implementation
- images.push(texImage._data);
- } else {
- console.log('copyTexImagesToTexture: Convert texImages to data buffers failed');
- return;
- }
- }
- }
- oldCopyTexImagesToTextureFunc.call(this, images, texture, regions);
- };
- const oldDeviceCreateSwapchainFunc = deviceProto.createSwapchain;
- deviceProto.createSwapchain = function (info) {
- info.windowHandle = window.windowHandler;
- return oldDeviceCreateSwapchainFunc.call(this, info);
- };
- const oldSwapchainInitializeFunc = swapchainProto.initialize;
- swapchainProto.initialize = function (info) {
- info.windowHandle = window.windowHandler;
- oldSwapchainInitializeFunc.call(this, info);
- };
- const oldUpdate = bufferProto.update;
- bufferProto.update = function (buffer, size) {
- if (buffer.byteLength === 0) return;
- let buffSize;
- if (this.cachedUsage & 0x40) {
- // BufferUsageBit.INDIRECT
- // It is a IIndirectBuffer object.
- const {
- drawInfos
- } = buffer;
- buffer = new Uint32Array(drawInfos.length * 7);
- let baseIndex = 0;
- let drawInfo;
- for (let i = 0; i < drawInfos.length; ++i) {
- baseIndex = i * 7;
- drawInfo = drawInfos[i];
- buffer[baseIndex] = drawInfo.vertexCount;
- buffer[baseIndex + 1] = drawInfo.firstVertex;
- buffer[baseIndex + 2] = drawInfo.indexCount;
- buffer[baseIndex + 3] = drawInfo.firstIndex;
- buffer[baseIndex + 4] = drawInfo.vertexOffset;
- buffer[baseIndex + 5] = drawInfo.instanceCount;
- buffer[baseIndex + 6] = drawInfo.firstInstance;
- }
- buffSize = buffer.byteLength;
- } else if (size !== undefined) {
- buffSize = size;
- } else {
- buffSize = buffer.byteLength;
- }
- oldUpdate.call(this, buffer, buffSize);
- };
- const oldDeviceCreateBufferFun = deviceProto.createBuffer;
- deviceProto.createBuffer = function (info) {
- let buffer;
- if (info.buffer) {
- buffer = oldDeviceCreateBufferFun.call(this, info, true);
- } else {
- buffer = oldDeviceCreateBufferFun.call(this, info, false);
- }
- buffer.cachedUsage = info.usage;
- return buffer;
- };
- const oldBufferInitializeFunc = bufferProto.initialize;
- bufferProto.initialize = function (info) {
- if (info.buffer) {
- oldBufferInitializeFunc.call(this, info, true);
- } else {
- oldBufferInitializeFunc.call(this, info, false);
- }
- };
- const oldDeviceCreateTextureFun = deviceProto.createTexture;
- deviceProto.createTexture = function (info) {
- if (info.texture) {
- return oldDeviceCreateTextureFun.call(this, info, true);
- }
- return oldDeviceCreateTextureFun.call(this, info, false);
- };
- const oldTextureInitializeFunc = textureProto.initialize;
- textureProto.initialize = function (info) {
- if (info.texture) {
- oldTextureInitializeFunc.call(this, info, true);
- } else {
- oldTextureInitializeFunc.call(this, info, false);
- }
- }; ///////////////////////////// optimizations /////////////////////////////
- // Cache dirty to avoid invoking gfx.DescriptorSet.update().
- descriptorSetProto.bindBuffer = function (binding, buffer, index) {
- this.dirtyJSB = descriptorSetProto.bindBufferJSB.call(this, binding, buffer, index || 0);
- };
- descriptorSetProto.bindSampler = function (binding, sampler, index) {
- this.dirtyJSB = descriptorSetProto.bindSamplerJSB.call(this, binding, sampler, index || 0);
- };
- descriptorSetProto.bindTexture = function (bindding, texture, index) {
- this.dirtyJSB = descriptorSetProto.bindTextureJSB.call(this, bindding, texture, index || 0);
- };
- const oldDSUpdate = descriptorSetProto.update;
- descriptorSetProto.update = function () {
- if (!this.dirtyJSB) return;
- oldDSUpdate.call(this);
- this.dirtyJSB = false;
- };
- Object.defineProperty(deviceProto, 'uboOffsetAlignment', {
- get() {
- if (this.cachedUboOffsetAlignment === undefined) {
- this.cachedUboOffsetAlignment = this.getUboOffsetAlignment();
- }
- return this.cachedUboOffsetAlignment;
- }
- });
- },{}],10:[function(require,module,exports){
- /****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- 'use strict';
- const cacheManager = require('./jsb-cache-manager');
- const {
- downloadFile,
- readText,
- readArrayBuffer,
- readJson,
- getUserDataPath,
- initJsbDownloader
- } = require('./jsb-fs-utils');
- const REGEX = /^\w+:\/\/.*/;
- const downloader = cc.assetManager.downloader;
- const parser = cc.assetManager.parser;
- const presets = cc.assetManager.presets;
- downloader.maxConcurrency = 30;
- downloader.maxRequestsPerFrame = 60;
- presets['preload'].maxConcurrency = 15;
- presets['preload'].maxRequestsPerFrame = 30;
- presets['scene'].maxConcurrency = 32;
- presets['scene'].maxRequestsPerFrame = 64;
- presets['bundle'].maxConcurrency = 32;
- presets['bundle'].maxRequestsPerFrame = 64;
- let suffix = 0;
- const failureMap = {};
- const maxRetryCountFromBreakpoint = 5;
- const loadedScripts = {};
- function downloadScript(url, options, onComplete) {
- if (typeof options === 'function') {
- onComplete = options;
- options = null;
- }
- if (loadedScripts[url]) return onComplete && onComplete();
- download(url, function (src, options, onComplete) {
- window.require(src);
- loadedScripts[url] = true;
- onComplete && onComplete(null);
- }, options, options.onFileProgress, onComplete);
- }
- function download(url, func, options, onFileProgress, onComplete) {
- var result = transformUrl(url, options);
- if (result.inLocal) {
- func(result.url, options, onComplete);
- } else if (result.inCache) {
- cacheManager.updateLastTime(url);
- func(result.url, options, function (err, data) {
- if (err) {
- cacheManager.removeCache(url);
- }
- onComplete(err, data);
- });
- } else {
- var time = Date.now();
- var storagePath = '';
- var failureRecord = failureMap[url];
- if (failureRecord) {
- storagePath = failureRecord.storagePath;
- } else if (options.__cacheBundleRoot__) {
- storagePath = `${options.__cacheBundleRoot__}/${time}${suffix++}${cc.path.extname(url)}`;
- } else {
- storagePath = `${time}${suffix++}${cc.path.extname(url)}`;
- }
- downloadFile(url, `${cacheManager.cacheDir}/${storagePath}`, options.header, onFileProgress, function (err, path) {
- if (err) {
- if (failureRecord) {
- failureRecord.retryCount++;
- if (failureRecord.retryCount >= maxRetryCountFromBreakpoint) {
- delete failureMap[url];
- }
- } else {
- failureMap[url] = {
- retryCount: 0,
- storagePath
- };
- }
- onComplete(err, null);
- return;
- }
- delete failureMap[url];
- func(path, options, function (err, data) {
- if (!err) {
- cacheManager.cacheFile(url, storagePath, options.__cacheBundleRoot__);
- }
- onComplete(err, data);
- });
- });
- }
- }
- function transformUrl(url, options) {
- var inLocal = false;
- var inCache = false;
- if (REGEX.test(url)) {
- if (options.reload) {
- return {
- url
- };
- } else {
- var cache = cacheManager.getCache(url);
- if (cache) {
- inCache = true;
- url = cache;
- }
- }
- } else {
- inLocal = true;
- }
- return {
- url,
- inLocal,
- inCache
- };
- }
- function doNothing(content, options, onComplete) {
- onComplete(null, content);
- }
- function downloadAsset(url, options, onComplete) {
- download(url, doNothing, options, options.onFileProgress, onComplete);
- }
- function _getFontFamily(fontHandle) {
- var ttfIndex = fontHandle.lastIndexOf(".ttf");
- if (ttfIndex === -1) return fontHandle;
- var slashPos = fontHandle.lastIndexOf("/");
- var fontFamilyName;
- if (slashPos === -1) {
- fontFamilyName = fontHandle.substring(0, ttfIndex) + "_LABEL";
- } else {
- fontFamilyName = fontHandle.substring(slashPos + 1, ttfIndex) + "_LABEL";
- }
- if (fontFamilyName.indexOf(' ') !== -1) {
- fontFamilyName = '"' + fontFamilyName + '"';
- }
- return fontFamilyName;
- }
- function parseText(url, options, onComplete) {
- readText(url, onComplete);
- }
- function parseJson(url, options, onComplete) {
- readJson(url, onComplete);
- }
- function downloadText(url, options, onComplete) {
- download(url, parseText, options, options.onFileProgress, onComplete);
- }
- function parseArrayBuffer(url, options, onComplete) {
- readArrayBuffer(url, onComplete);
- }
- function downloadJson(url, options, onComplete) {
- download(url, parseJson, options, options.onFileProgress, onComplete);
- }
- function downloadBundle(nameOrUrl, options, onComplete) {
- let bundleName = cc.path.basename(nameOrUrl);
- var version = options.version || downloader.bundleVers[bundleName];
- let url;
- if (REGEX.test(nameOrUrl) || nameOrUrl.startsWith(getUserDataPath())) {
- url = nameOrUrl;
- cacheManager.makeBundleFolder(bundleName);
- } else {
- if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
- url = `${downloader.remoteServerAddress}remote/${bundleName}`;
- cacheManager.makeBundleFolder(bundleName);
- } else {
- url = `assets/${bundleName}`;
- }
- }
- var config = `${url}/cc.config.${version ? version + '.' : ''}json`;
- options.__cacheBundleRoot__ = bundleName;
- downloadJson(config, options, function (err, response) {
- if (err) {
- return onComplete(err, null);
- }
- let out = response;
- out && (out.base = url + '/');
- var js = `${url}/index.${version ? version + '.' : ''}${out.encrypted ? 'jsc' : `js`}`;
- downloadScript(js, options, function (err) {
- if (err) {
- return onComplete(err, null);
- }
- onComplete(null, out);
- });
- });
- }
- ;
- const downloadCCON = (url, options, onComplete) => {
- downloadJson(url, options, (err, json) => {
- if (err) {
- onComplete(err);
- return;
- }
- const cconPreface = cc.internal.parseCCONJson(json);
- const chunkPromises = Promise.all(cconPreface.chunks.map(chunk => new Promise((resolve, reject) => {
- downloadArrayBuffer(`${cc.path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => {
- if (errChunk) {
- reject(errChunk);
- } else {
- resolve(new Uint8Array(chunkBuffer));
- }
- });
- })));
- chunkPromises.then(chunks => {
- const ccon = new cc.internal.CCON(cconPreface.document, chunks);
- onComplete(null, ccon);
- }).catch(err => {
- onComplete(err);
- });
- });
- };
- const downloadCCONB = (url, options, onComplete) => {
- downloadArrayBuffer(url, options, (err, arrayBuffer) => {
- if (err) {
- onComplete(err);
- return;
- }
- try {
- const ccon = cc.internal.decodeCCONBinary(new Uint8Array(arrayBuffer));
- onComplete(null, ccon);
- } catch (err) {
- onComplete(err);
- }
- });
- };
- function downloadArrayBuffer(url, options, onComplete) {
- download(url, parseArrayBuffer, options, options.onFileProgress, onComplete);
- }
- function loadFont(url, options, onComplete) {
- let fontFamilyName = _getFontFamily(url);
- let fontFace = new FontFace(fontFamilyName, "url('" + url + "')");
- document.fonts.add(fontFace);
- fontFace.load();
- fontFace.loaded.then(function () {
- onComplete(null, fontFamilyName);
- }, function () {
- cc.warnID(4933, fontFamilyName);
- onComplete(null, fontFamilyName);
- });
- }
- const originParsePlist = parser.parsePlist;
- let parsePlist = function (url, options, onComplete) {
- readText(url, function (err, file) {
- if (err) return onComplete(err);
- originParsePlist(file, options, onComplete);
- });
- };
- parser.parsePVRTex = downloader.downloadDomImage;
- parser.parsePKMTex = downloader.downloadDomImage;
- parser.parseASTCTex = downloader.downloadDomImage;
- parser.parsePlist = parsePlist;
- downloader.downloadScript = downloadScript;
- function loadAudioPlayer(url, options, onComplete) {
- cc.AudioPlayer.load(url).then(player => {
- const audioMeta = {
- player,
- url,
- duration: player.duration,
- type: player.type
- };
- onComplete(null, audioMeta);
- }).catch(err => {
- onComplete(err);
- });
- }
- downloader.register({
- // JS
- '.js': downloadScript,
- '.jsc': downloadScript,
- // Images
- '.png': downloadAsset,
- '.jpg': downloadAsset,
- '.bmp': downloadAsset,
- '.jpeg': downloadAsset,
- '.gif': downloadAsset,
- '.ico': downloadAsset,
- '.tiff': downloadAsset,
- '.webp': downloadAsset,
- '.image': downloadAsset,
- '.pvr': downloadAsset,
- '.pkm': downloadAsset,
- '.astc': downloadAsset,
- // Audio
- '.mp3': downloadAsset,
- '.ogg': downloadAsset,
- '.wav': downloadAsset,
- '.m4a': downloadAsset,
- '.ccon': downloadCCON,
- '.cconb': downloadCCONB,
- // Video
- '.mp4': downloadAsset,
- '.avi': downloadAsset,
- '.mov': downloadAsset,
- '.mpg': downloadAsset,
- '.mpeg': downloadAsset,
- '.rm': downloadAsset,
- '.rmvb': downloadAsset,
- // Text
- '.txt': downloadAsset,
- '.xml': downloadAsset,
- '.vsh': downloadAsset,
- '.fsh': downloadAsset,
- '.atlas': downloadAsset,
- '.tmx': downloadAsset,
- '.tsx': downloadAsset,
- '.fnt': downloadAsset,
- '.plist': downloadAsset,
- '.json': downloadJson,
- '.ExportJson': downloadAsset,
- '.binary': downloadAsset,
- '.bin': downloadAsset,
- '.dbbin': downloadAsset,
- '.skel': downloadAsset,
- // Font
- '.font': downloadAsset,
- '.eot': downloadAsset,
- '.ttf': downloadAsset,
- '.woff': downloadAsset,
- '.svg': downloadAsset,
- '.ttc': downloadAsset,
- 'bundle': downloadBundle,
- 'default': downloadText
- });
- parser.register({
- // Images
- '.png': downloader.downloadDomImage,
- '.jpg': downloader.downloadDomImage,
- '.bmp': downloader.downloadDomImage,
- '.jpeg': downloader.downloadDomImage,
- '.gif': downloader.downloadDomImage,
- '.ico': downloader.downloadDomImage,
- '.tiff': downloader.downloadDomImage,
- '.webp': downloader.downloadDomImage,
- '.image': downloader.downloadDomImage,
- // Audio
- '.mp3': loadAudioPlayer,
- '.ogg': loadAudioPlayer,
- '.wav': loadAudioPlayer,
- '.m4a': loadAudioPlayer,
- // compressed texture
- '.pvr': downloader.downloadDomImage,
- '.pkm': downloader.downloadDomImage,
- '.astc': downloader.downloadDomImage,
- '.binary': parseArrayBuffer,
- '.bin': parseArrayBuffer,
- '.dbbin': parseArrayBuffer,
- '.skel': parseArrayBuffer,
- // Text
- '.txt': parseText,
- '.xml': parseText,
- '.vsh': parseText,
- '.fsh': parseText,
- '.atlas': parseText,
- '.tmx': parseText,
- '.tsx': parseText,
- '.fnt': parseText,
- '.plist': parsePlist,
- // Font
- '.font': loadFont,
- '.eot': loadFont,
- '.ttf': loadFont,
- '.woff': loadFont,
- '.svg': loadFont,
- '.ttc': loadFont,
- '.ExportJson': parseJson
- });
- cc.assetManager.transformPipeline.append(function (task) {
- var input = task.output = task.input;
- for (var i = 0, l = input.length; i < l; i++) {
- var item = input[i];
- if (item.config) {
- item.options.__cacheBundleRoot__ = item.config.name;
- }
- if (item.ext === '.cconb') {
- item.url = item.url.replace(item.ext, '.bin');
- } else if (item.ext === '.ccon') {
- item.url = item.url.replace(item.ext, '.json');
- }
- }
- });
- var originInit = cc.assetManager.init;
- cc.assetManager.init = function (options) {
- originInit.call(cc.assetManager, options);
- const jsbDownloaderMaxTasks = cc.settings.querySettings('assets', 'jsbDownloaderMaxTasks');
- const jsbDownloaderTimeout = cc.settings.querySettings('assets', 'jsbDownloaderTimeout');
- initJsbDownloader(jsbDownloaderMaxTasks, jsbDownloaderTimeout);
- cacheManager.init();
- };
- },{"./jsb-cache-manager":3,"./jsb-fs-utils":7}],11:[function(require,module,exports){
- "use strict";
- const jsbPhy = globalThis['jsb.physics'];
- jsbPhy.CACHE = {
- trimesh: {},
- convex: {},
- height: {},
- material: {}
- };
- jsbPhy.OBJECT = {
- books: [],
- ptrToObj: {},
- raycastOptions: {
- origin: null,
- unitDir: null,
- distance: 0,
- mask: 0,
- queryTrigger: true
- }
- };
- jsbPhy.CONFIG = {
- heightScale: 1 / 512
- };
- const books = jsbPhy.OBJECT.books;
- const ptrToObj = jsbPhy.OBJECT.ptrToObj;
- const raycastOptions = jsbPhy.OBJECT.raycastOptions;
- const TriggerEventObject = {
- type: 'onTriggerEnter',
- selfCollider: null,
- otherCollider: null,
- impl: null
- };
- const CollisionEventObject = {
- type: 'onCollisionEnter',
- selfCollider: null,
- otherCollider: null,
- contacts: [],
- impl: null
- };
- function emitTriggerEvent(t, c0, c1, impl) {
- TriggerEventObject.type = t;
- TriggerEventObject.impl = impl;
- if (c0.needTriggerEvent) {
- TriggerEventObject.selfCollider = c0;
- TriggerEventObject.otherCollider = c1;
- c0.emit(t, TriggerEventObject);
- }
- if (c1.needTriggerEvent) {
- TriggerEventObject.selfCollider = c1;
- TriggerEventObject.otherCollider = c0;
- c1.emit(t, TriggerEventObject);
- }
- }
- const quat = new cc.Quat();
- const contactsPool = [];
- const contactBufferElementLength = 12;
- class ContactPoint {
- constructor(e) {
- this.event = e;
- this.impl = null;
- this.colliderA = null;
- this.colliderB = null;
- this.index = 0;
- }
- get isBodyA() {
- return this.colliderA.uuid === this.event.selfCollider.uuid;
- }
- getLocalPointOnA(o) {
- this.getWorldPointOnB(o);
- cc.Vec3.subtract(o, o, this.colliderA.node.worldPosition);
- }
- getLocalPointOnB(o) {
- this.getWorldPointOnB(o);
- cc.Vec3.subtract(o, o, this.colliderB.node.worldPosition);
- }
- getWorldPointOnA(o) {
- this.getWorldPointOnB(o);
- }
- getWorldPointOnB(o) {
- const i = this.index * contactBufferElementLength;
- o.x = this.impl[i];
- o.y = this.impl[i + 1];
- o.z = this.impl[i + 2];
- }
- getLocalNormalOnA(o) {
- this.getWorldNormalOnA(o);
- cc.Quat.conjugate(quat, this.colliderA.node.worldRotation);
- cc.Vec3.transformQuat(o, o, quat);
- }
- getLocalNormalOnB(o) {
- this.getWorldNormalOnB(o);
- cc.Quat.conjugate(quat, this.colliderB.node.worldRotation);
- cc.Vec3.transformQuat(out, out, quat);
- }
- getWorldNormalOnA(o) {
- this.getWorldNormalOnB(o);
- if (!this.isBodyA) cc.Vec3.negate(o, o);
- }
- getWorldNormalOnB(o) {
- const i = this.index * contactBufferElementLength + 3;
- o.x = this.impl[i];
- o.y = this.impl[i + 1];
- o.z = this.impl[i + 2];
- }
- }
- function emitCollisionEvent(t, c0, c1, impl, b) {
- CollisionEventObject.type = t;
- CollisionEventObject.impl = impl;
- const contacts = CollisionEventObject.contacts;
- contactsPool.push.apply(contactsPool, contacts);
- contacts.length = 0;
- const contactCount = b.length / contactBufferElementLength;
- for (let i = 0; i < contactCount; i++) {
- const c = contactsPool.length > 0 ? contactsPool.pop() : new ContactPoint(CollisionEventObject);
- c.colliderA = c0;
- c.colliderB = c1;
- c.impl = b;
- c.index = i;
- contacts.push(c);
- }
- if (c0.needCollisionEvent) {
- CollisionEventObject.selfCollider = c0;
- CollisionEventObject.otherCollider = c1;
- c0.emit(t, CollisionEventObject);
- }
- if (c1.needCollisionEvent) {
- CollisionEventObject.selfCollider = c1;
- CollisionEventObject.otherCollider = c0;
- c1.emit(t, CollisionEventObject);
- }
- }
- class PhysicsWorld {
- get impl() {
- return this._impl;
- }
- constructor() {
- this._impl = new jsbPhy.World();
- }
- setGravity(v) {
- this._impl.setGravity(v.x, v.y, v.z);
- }
- setAllowSleep(v) {
- this._impl.setAllowSleep(v);
- }
- setDefaultMaterial(v) {}
- step(f, t, m) {
- // books.forEach((v) => { v.syncToNativeTransform(); });
- this._impl.step(f);
- }
- raycast(r, o, p, rs) {
- raycastOptions.origin = r.o;
- raycastOptions.unitDir = r.d;
- raycastOptions.mask = o.mask >>> 0;
- raycastOptions.distance = o.maxDistance;
- raycastOptions.queryTrigger = !!o.queryTrigger;
- const isHit = this._impl.raycast(raycastOptions);
- if (isHit) {
- const hits = this._impl.raycastResult();
- for (let i = 0; i < hits.length; i++) {
- const hit = hits[i];
- const out = p.add();
- out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
- rs.push(out);
- }
- }
- return isHit;
- }
- raycastClosest(r, o, out) {
- raycastOptions.origin = r.o;
- raycastOptions.unitDir = r.d;
- raycastOptions.mask = o.mask >>> 0;
- raycastOptions.distance = o.maxDistance;
- raycastOptions.queryTrigger = !!o.queryTrigger;
- const isHit = this._impl.raycastClosest(raycastOptions);
- if (isHit) {
- const hit = this._impl.raycastClosestResult();
- out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
- }
- return isHit;
- }
- emitEvents() {
- this.emitTriggerEvent();
- this.emitCollisionEvent();
- this._impl.emitEvents();
- }
- syncSceneToPhysics() {
- this._impl.syncSceneToPhysics();
- }
- syncAfterEvents() {// this._impl.syncSceneToPhysics()
- }
- destroy() {
- this._impl.destroy();
- }
- emitTriggerEvent() {
- const teps = this._impl.getTriggerEventPairs();
- const len = teps.length / 3;
- for (let i = 0; i < len; i++) {
- const t = i * 3;
- const sa = ptrToObj[teps[t + 0]];
- const sb = ptrToObj[teps[t + 1]];
- if (!sa || !sb) continue;
- const c0 = sa.collider;
- const c1 = sb.collider;
- if (!(c0 && c0.isValid && c1 && c1.isValid)) continue;
- if (!c0.needTriggerEvent && !c1.needTriggerEvent) continue;
- const state = teps[t + 2];
- if (state === 1) {
- emitTriggerEvent('onTriggerStay', c0, c1, teps);
- } else if (state === 0) {
- emitTriggerEvent('onTriggerEnter', c0, c1, teps);
- } else {
- emitTriggerEvent('onTriggerExit', c0, c1, teps);
- }
- }
- }
- emitCollisionEvent() {
- const ceps = this._impl.getContactEventPairs();
- const len2 = ceps.length / 4;
- for (let i = 0; i < len2; i++) {
- const t = i * 4;
- const sa = ptrToObj[ceps[t + 0]];
- const sb = ptrToObj[ceps[t + 1]];
- if (!sa || !sb) continue;
- const c0 = sa.collider;
- const c1 = sb.collider;
- if (!(c0 && c0.isValid && c1 && c1.isValid)) continue;
- if (!c0.needCollisionEvent && !c1.needCollisionEvent) continue;
- const state = ceps[t + 2];
- if (state === 1) {
- emitCollisionEvent('onCollisionStay', c0, c1, ceps, ceps[t + 3]);
- } else if (state === 0) {
- emitCollisionEvent('onCollisionEnter', c0, c1, ceps, ceps[t + 3]);
- } else {
- emitCollisionEvent('onCollisionExit', c0, c1, ceps, ceps[t + 3]);
- }
- }
- }
- }
- function bookNode(v) {
- if (v._physicsBookIndex === undefined) {
- v._physicsBookIndex = books.length;
- books.push(v);
- }
- }
- function unBookNode(v) {
- const index = v._physicsBookIndex;
- if (index !== undefined) {
- books[index] = books[books.length - 1];
- books[index]._physicsBookIndex = index;
- books.length -= 1;
- v._physicsBookIndex = undefined;
- }
- }
- function updateCollisionMatrix() {
- const phy = cc.PhysicsSystem.instance;
- const world = phy.physicsWorld.impl;
- const cm = phy.collisionMatrix;
- if (cm.updateArray && cm.updateArray.length > 0) {
- cm.updateArray.forEach(e => {
- const key = `${1 << e}`;
- const mask = cm[key];
- world.setCollisionMatrix(e, mask);
- });
- cm.updateArray.length = 0;
- }
- }
- class RigidBody {
- get impl() {
- return this._impl;
- }
- get rigidBody() {
- return this._com;
- }
- get isAwake() {
- return this._impl.isAwake();
- }
- get isSleepy() {
- return false;
- }
- get isSleeping() {
- return this._impl.isSleeping();
- }
- constructor() {
- updateCollisionMatrix();
- this._impl = new jsbPhy.RigidBody();
- this._isUsingCCD = false;
- }
- initialize(v) {
- v.node.updateWorldTransform();
- this._com = v;
- this._impl.initialize(v.node, v.type, v._group);
- bookNode(v.node);
- }
- onEnable() {
- this.setType(this._com.type);
- this.setMass(this._com.mass);
- this.setAllowSleep(this._com.allowSleep);
- this.setLinearDamping(this._com.linearDamping);
- this.setAngularDamping(this._com.angularDamping);
- this.setLinearFactor(this._com.linearFactor);
- this.setAngularFactor(this._com.angularFactor);
- this.useGravity(this._com.useGravity);
- this._impl.onEnable();
- }
- onDisable() {
- this._impl.onDisable();
- }
- onDestroy() {
- unBookNode(this._com.node);
- this._impl.onDestroy();
- }
- setGroup(v) {
- this._impl.setGroup(v);
- }
- getGroup() {
- return this._impl.getGroup();
- }
- addGroup(v) {
- this.setGroup(this.getGroup() | v);
- }
- removeGroup(v) {
- this.setGroup(this.getGroup() & ~v);
- }
- setMask(v) {
- this._impl.setMask(v >>> 0);
- }
- getMask() {
- return this._impl.getMask();
- }
- addMask(v) {
- this.setMask(this.getMask() | v);
- }
- removeMask(v) {
- this.setMask(this.getMask() & ~v);
- }
- setType(v) {
- this._impl.setType(v);
- }
- setMass(v) {
- this._impl.setMass(v);
- }
- setAllowSleep(v) {
- this._impl.setAllowSleep(v);
- }
- setLinearDamping(v) {
- const dt = cc.PhysicsSystem.instance.fixedTimeStep;
- this._impl.setLinearDamping((1 - (1 - v) ** dt) / dt);
- }
- setAngularDamping(v) {
- const dt = cc.PhysicsSystem.instance.fixedTimeStep;
- this._impl.setAngularDamping((1 - (1 - v) ** dt) / dt);
- }
- isUsingCCD() {
- return this._isUsingCCD;
- }
- useCCD(v) {
- this._isUsingCCD = v;
- return this._impl.useCCD(v);
- }
- useGravity(v) {
- this._impl.useGravity(v);
- }
- setLinearFactor(v) {
- this._impl.setLinearFactor(v.x, v.y, v.z);
- }
- setAngularFactor(v) {
- this._impl.setAngularFactor(v.x, v.y, v.z);
- }
- wakeUp() {
- this._impl.wakeUp();
- }
- sleep() {
- this._impl.sleep();
- }
- clearState() {
- this._impl.clearState();
- }
- clearForces() {
- this._impl.clearForces();
- }
- clearVelocity() {
- this._impl.clearVelocity();
- }
- setSleepThreshold(v) {
- this._impl.setSleepThreshold(v);
- }
- getSleepThreshold() {
- return this._impl.getSleepThreshold();
- }
- getLinearVelocity(o) {
- o.set(this._impl.getLinearVelocity());
- }
- setLinearVelocity(v) {
- this._impl.setLinearVelocity(v.x, v.y, v.z);
- }
- getAngularVelocity(o) {
- o.set(this._impl.getAngularVelocity());
- }
- setAngularVelocity(v) {
- this._impl.setAngularVelocity(v.x, v.y, v.z);
- }
- applyForce(f, p) {
- if (p == null) {
- p = cc.Vec3.ZERO;
- }
- this._impl.applyForce(f.x, f.y, f.z, p.x, p.y, p.z);
- }
- applyLocalForce(f, p) {
- if (p == null) {
- p = cc.Vec3.ZERO;
- }
- this._impl.applyLocalForce(f.x, f.y, f.z, p.x, p.y, p.z);
- }
- applyImpulse(f, p) {
- if (p == null) {
- p = cc.Vec3.ZERO;
- }
- this._impl.applyImpulse(f.x, f.y, f.z, p.x, p.y, p.z);
- }
- applyLocalImpulse(f, p) {
- if (p == null) {
- p = cc.Vec3.ZERO;
- }
- this._impl.applyLocalImpulse(f.x, f.y, f.z, p.x, p.y, p.z);
- }
- applyTorque(t) {
- this._impl.applyTorque(t.x, t.y, t.z);
- }
- applyLocalTorque(t) {
- this._impl.applyLocalTorque(t.x, t.y, t.z);
- }
- }
- const ESHAPE_FLAG = {
- NONE: 0,
- QUERY_FILTER: 1 << 0,
- QUERY_SINGLE_HIT: 1 << 2,
- DETECT_TRIGGER_EVENT: 1 << 3,
- DETECT_CONTACT_EVENT: 1 << 4,
- DETECT_CONTACT_POINT: 1 << 5,
- DETECT_CONTACT_CCD: 1 << 6
- };
- class Shape {
- get impl() {
- return this._impl;
- }
- get collider() {
- return this._com;
- }
- get attachedRigidBody() {
- return this._attachedRigidBody;
- }
- constructor() {
- updateCollisionMatrix();
- }
- initialize(v) {
- v.node.updateWorldTransform();
- this._com = v;
- this._impl.initialize(v.node);
- ptrToObj[this._impl.getObjectID()] = this;
- bookNode(v.node);
- }
- onLoad() {
- this.setMaterial(this._com.sharedMaterial);
- this.setCenter(this._com.center);
- this.setAsTrigger(this._com.isTrigger);
- }
- onEnable() {
- this._impl.onEnable();
- }
- onDisable() {
- this._impl.onDisable();
- }
- onDestroy() {
- unBookNode(this._com.node);
- delete ptrToObj[this._impl.getObjectID()];
- ptrToObj[this._impl.getObjectID()] = null;
- this._impl.onDestroy();
- }
- setMaterial(v) {
- const ins = cc.PhysicsSystem.instance;
- if (!v) v = ins.defaultMaterial;
- if (!jsbPhy.CACHE.material[v.id]) {
- jsbPhy.CACHE.material[v.id] = ins.physicsWorld.impl.createMaterial(v.id, v.friction, v.friction, v.restitution, 2, 2);
- }
- this._impl.setMaterial(v.id, v.friction, v.friction, v.restitution, 2, 2);
- }
- setAsTrigger(v) {
- this._impl.setAsTrigger(v);
- }
- setCenter(v) {
- this._impl.setCenter(v.x, v.y, v.z);
- }
- getAABB(v) {
- v.copy(this._impl.getAABB());
- }
- getBoundingSphere(v) {
- v.copy(this._impl.getBoundingSphere());
- }
- updateEventListener() {
- let flag = 0;
- flag |= ESHAPE_FLAG.DETECT_CONTACT_CCD;
- if (this._com.isTrigger) flag |= ESHAPE_FLAG.IS_TRIGGER;
- if (this._com.needTriggerEvent || this._com.needCollisionEvent) flag |= ESHAPE_FLAG.NEED_EVENT;
- this._impl.updateEventListener(flag);
- }
- setGroup(v) {
- this._impl.setGroup(v);
- }
- getGroup() {
- return this._impl.getGroup();
- }
- addGroup(v) {
- this.setGroup(this.getGroup() | v);
- }
- removeGroup(v) {
- this.setGroup(this.getGroup() & ~v);
- }
- setMask(v) {
- this._impl.setMask(v >>> 0);
- }
- getMask() {
- return this._impl.getMask();
- }
- addMask(v) {
- this.setMask(this.getMask() | v);
- }
- removeMask(v) {
- this.setMask(this.getMask() & ~v);
- }
- }
- class SphereShape extends Shape {
- constructor() {
- super();
- this._impl = new jsbPhy.SphereShape();
- }
- updateRadius() {
- this._impl.setRadius(this.collider.radius);
- }
- onLoad() {
- super.onLoad();
- this.updateRadius();
- }
- }
- class BoxShape extends Shape {
- constructor() {
- super();
- this._impl = new jsbPhy.BoxShape();
- }
- updateSize() {
- const v = this.collider.size;
- this._impl.setSize(v.x, v.y, v.z);
- }
- onLoad() {
- super.onLoad();
- this.updateSize();
- }
- }
- class CapsuleShape extends Shape {
- constructor() {
- super();
- this._impl = new jsbPhy.CapsuleShape();
- }
- setRadius(v) {
- this._impl.setRadius(v);
- }
- setDirection(v) {
- this._impl.setDirection(v);
- }
- setCylinderHeight(v) {
- this._impl.setCylinderHeight(v);
- }
- onLoad() {
- super.onLoad();
- this.setRadius(this._com.radius);
- this.setDirection(this._com.direction);
- this.setCylinderHeight(this._com.cylinderHeight);
- }
- }
- class PlaneShape extends Shape {
- constructor() {
- super();
- this._impl = new jsbPhy.PlaneShape();
- }
- setConstant(v) {
- this._impl.setConstant(v);
- }
- setNormal(v) {
- this._impl.setNormal(v.x, v.y, v.z);
- }
- onLoad() {
- super.onLoad();
- this.setNormal(this._com.normal);
- this.setConstant(this._com.constant);
- }
- }
- function getConvexMesh(v) {
- if (!jsbPhy.CACHE.convex[v._uuid]) {
- const posArr = cc.physics.utils.shrinkPositions(v.readAttribute(0, 'a_position'));
- const world = cc.PhysicsSystem.instance.physicsWorld.impl;
- const convex = {
- positions: new Float32Array(posArr),
- positionLength: posArr.length / 3
- };
- jsbPhy.CACHE.convex[v._uuid] = world.createConvex(convex);
- }
- return jsbPhy.CACHE.convex[v._uuid];
- }
- function getTriangleMesh(v) {
- if (!jsbPhy.CACHE.trimesh[v._uuid]) {
- const indArr = v.readIndices(0); // const posArr = cc.physics.utils.shrinkPositions(v.readAttribute(0, 'a_position'));
- const posArr = v.readAttribute(0, 'a_position');
- const world = cc.PhysicsSystem.instance.physicsWorld.impl;
- const trimesh = {
- positions: new Float32Array(posArr),
- positionLength: posArr.length / 3,
- triangles: new Uint16Array(indArr),
- triangleLength: indArr.length / 3,
- isU16: true
- };
- jsbPhy.CACHE.trimesh[v._uuid] = world.createTrimesh(trimesh);
- }
- return jsbPhy.CACHE.trimesh[v._uuid];
- }
- function getHeightField(v) {
- if (!jsbPhy.CACHE.height[v._uuid]) {
- const rows = v.getVertexCountI();
- const columns = v.getVertexCountJ();
- const samples = new Int16Array(rows * columns);
- const heightScale = jsbPhy.CONFIG.heightScale;
- for (let i = 0; i < rows; i++) {
- for (let j = 0; j < columns; j++) {
- samples[j + i * columns] = v.getHeight(i, j) / heightScale;
- }
- }
- const height = {
- rows,
- columns,
- samples
- };
- const world = cc.PhysicsSystem.instance.physicsWorld.impl;
- jsbPhy.CACHE.height[v._uuid] = world.createHeightField(height);
- }
- return jsbPhy.CACHE.height[v._uuid];
- }
- class CylinderShape extends Shape {
- constructor() {
- super();
- this._impl = new jsbPhy.CylinderShape();
- }
- setRadius(v) {
- this.updateGeometry();
- }
- setDirection(v) {
- this.updateGeometry();
- }
- setHeight(v) {
- this.updateGeometry();
- }
- updateGeometry() {
- this._impl.setCylinder(this._com.radius, this._com.height, this._com.direction);
- }
- initialize(v) {
- if (!jsbPhy.CACHE.convex.CYLINDER) {
- const primitive = cc.physics.utils.cylinder(0.5, 0.5, 2, {
- radialSegments: 32,
- heightSegments: 1
- });
- const posArr = cc.physics.utils.shrinkPositions(primitive.positions);
- const convex = {
- positions: new Float32Array(posArr),
- positionLength: posArr.length / 3
- };
- const pxObjectID = cc.PhysicsSystem.instance.physicsWorld.impl.createConvex(convex);
- jsbPhy.CACHE.convex.CYLINDER = pxObjectID;
- }
- this._com = v;
- this._impl.setCylinder(v.radius, v.height, v.direction);
- this._impl.setConvex(jsbPhy.CACHE.convex.CYLINDER);
- super.initialize(v);
- }
- }
- class ConeShape extends Shape {
- constructor() {
- super();
- this._impl = new jsbPhy.ConeShape();
- }
- setRadius(v) {
- this.updateGeometry();
- }
- setDirection(v) {
- this.updateGeometry();
- }
- setHeight(v) {
- this.updateGeometry();
- }
- updateGeometry() {
- this._impl.setCone(this._com.radius, this._com.height, this._com.direction);
- }
- initialize(v) {
- if (!jsbPhy.CACHE.convex.CONE) {
- const primitive = cc.physics.utils.cylinder(0, 0.5, 1, {
- radialSegments: 32,
- heightSegments: 1
- });
- const posArr = cc.physics.utils.shrinkPositions(primitive.positions);
- const convex = {
- positions: new Float32Array(posArr),
- positionLength: posArr.length / 3
- };
- const pxObjectID = cc.PhysicsSystem.instance.physicsWorld.impl.createConvex(convex);
- jsbPhy.CACHE.convex.CONE = pxObjectID;
- }
- this._com = v;
- this._impl.setCone(v.radius, v.height, v.direction);
- this._impl.setConvex(jsbPhy.CACHE.convex.CONE);
- super.initialize(v);
- }
- }
- class TrimeshShape extends Shape {
- constructor() {
- super();
- this._impl = new jsbPhy.TrimeshShape();
- }
- setConvex(v) {
- this._impl.useConvex(v);
- }
- setMesh(v) {
- if (!v) return;
- const isConvex = this._com.convex;
- this._impl.useConvex(isConvex);
- const pxObjectID = isConvex ? getConvexMesh(v) : getTriangleMesh(v);
- this._impl.setMesh(pxObjectID);
- }
- initialize(v) {
- this._com = v;
- this.setConvex(v.convex);
- this.setMesh(v.mesh);
- super.initialize(v);
- }
- }
- class TerrainShape extends Shape {
- constructor() {
- super();
- this._impl = new jsbPhy.TerrainShape();
- }
- setTerrain(v) {
- if (!v) return;
- const pxObjectID = getHeightField(v);
- this._impl.setTerrain(pxObjectID, v.tileSize, v.tileSize, jsbPhy.CONFIG.heightScale);
- }
- initialize(v) {
- this._com = v;
- this.setTerrain(v.terrain);
- super.initialize(v);
- }
- }
- class Joint {
- get impl() {
- return this._impl;
- }
- get joint() {
- return this._com;
- }
- setEnableCollision(v) {
- this._impl.setEnableCollision(v);
- }
- setConnectedBody(v) {
- this._impl.setConnectedBody(v ? v.body.impl.getObjectID() : 0);
- }
- initialize(v) {
- this._com = v;
- this._impl.initialize(v.node);
- ptrToObj[this._impl.getObjectID()] = this;
- this.onLoad();
- }
- onLoad() {
- this.setConnectedBody(this._com.connectedBody);
- this.setEnableCollision(this._com.enableCollision);
- }
- onEnable() {
- this._impl.onEnable();
- }
- onDisable() {
- this._impl.onDisable();
- }
- onDestroy() {
- delete ptrToObj[this._impl.getObjectID()];
- ptrToObj[this._impl.getObjectID()] = null;
- this._impl.onDestroy();
- }
- }
- class DistanceJoint extends Joint {
- constructor() {
- super();
- this._impl = new jsbPhy.DistanceJoint();
- }
- setPivotA(v) {
- this._impl.setPivotA(v.x, v.y, v.z);
- }
- setPivotB(v) {
- this._impl.setPivotB(v.x, v.y, v.z);
- }
- onLoad() {
- super.onLoad();
- this.setPivotA(this._com.pivotA);
- this.setPivotB(this._com.pivotB);
- }
- }
- class RevoluteJoint extends Joint {
- constructor() {
- super();
- this._impl = new jsbPhy.RevoluteJoint();
- }
- setAxis(v) {
- this._impl.setAxis(v.x, v.y, v.z);
- }
- setPivotA(v) {
- this._impl.setPivotA(v.x, v.y, v.z);
- }
- setPivotB(v) {
- this._impl.setPivotB(v.x, v.y, v.z);
- }
- onLoad() {
- super.onLoad();
- this.setAxis(this._com.axis);
- this.setPivotA(this._com.pivotA);
- this.setPivotB(this._com.pivotB);
- }
- }
- cc.physics.selector.register('physx', {
- PhysicsWorld,
- RigidBody,
- SphereShape,
- BoxShape,
- PlaneShape,
- CapsuleShape,
- ConeShape,
- CylinderShape,
- TrimeshShape,
- TerrainShape,
- PointToPointConstraint: DistanceJoint,
- HingeConstraint: RevoluteJoint
- });
- },{}],12:[function(require,module,exports){
- "use strict";
- /****************************************************************************
- Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
- http://www.cocos.com
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- const cacheManager = require('./jsb-cache-manager'); // @ts-expect-error jsb polyfills
- (function () {
- if (window.spine === undefined || window.middleware === undefined) return;
- if (cc.internal.SpineSkeletonData === undefined) return;
- const spine = window.spine;
- const middleware = window.middleware;
- middleware.generateGetSet(spine); // spine global time scale
- Object.defineProperty(spine, 'timeScale', {
- get() {
- return this._timeScale;
- },
- set(value) {
- this._timeScale = value;
- spine.SkeletonAnimation.setGlobalTimeScale(value);
- },
- configurable: true
- });
- const _slotColor = cc.color(0, 0, 255, 255);
- const _boneColor = cc.color(255, 0, 0, 255);
- const _meshColor = cc.color(255, 255, 0, 255);
- const _originColor = cc.color(0, 255, 0, 255);
- const skeletonDataProto = cc.internal.SpineSkeletonData.prototype;
- let _gTextureIdx = 1;
- const _textureKeyMap = {};
- const _textureMap = new WeakMap();
- const skeletonDataMgr = spine.SkeletonDataMgr.getInstance();
- spine.skeletonDataMgr = skeletonDataMgr;
- skeletonDataMgr.setDestroyCallback(textureIndex => {
- if (!textureIndex) return;
- const texKey = _textureKeyMap[textureIndex];
- if (texKey && _textureMap.has(texKey)) {
- _textureMap.delete(texKey);
- delete _textureKeyMap[textureIndex];
- }
- });
- const skeletonCacheMgr = spine.SkeletonCacheMgr.getInstance();
- spine.skeletonCacheMgr = skeletonCacheMgr;
- skeletonDataProto.destroy = function () {
- this.reset();
- skeletonCacheMgr.removeSkeletonCache(this._uuid);
- cc.Asset.prototype.destroy.call(this);
- };
- skeletonDataProto.reset = function () {
- if (this._skeletonCache) {
- spine.disposeSkeletonData(this._uuid);
- this._jsbTextures = null;
- this._skeletonCache = null;
- }
- this._atlasCache = null;
- };
- skeletonDataProto.getRuntimeData = function () {
- if (!this._skeletonCache) {
- this.init();
- }
- return this._skeletonCache;
- };
- skeletonDataProto.init = function () {
- if (this._skeletonCache) return;
- const uuid = this._uuid;
- if (!uuid) {
- cc.errorID(7504);
- return;
- }
- const atlasText = this.atlasText;
- if (!atlasText) {
- cc.errorID(7508, this.name);
- return;
- }
- const textures = this.textures;
- const textureNames = this.textureNames;
- if (!(textures && textures.length > 0 && textureNames && textureNames.length > 0)) {
- cc.errorID(7507, this.name);
- return;
- }
- const jsbTextures = {};
- for (let i = 0; i < textures.length; ++i) {
- const texture = textures[i];
- const textureIdx = this.recordTexture(texture);
- const spTex = new middleware.Texture2D();
- spTex.setRealTextureIndex(textureIdx);
- spTex.setPixelsWide(texture.width);
- spTex.setPixelsHigh(texture.height);
- spTex.setRealTexture(texture);
- jsbTextures[textureNames[i]] = spTex;
- }
- this._jsbTextures = jsbTextures;
- let filePath = null;
- if (this.skeletonJsonStr) {
- filePath = this.skeletonJsonStr;
- } else {
- filePath = cacheManager.getCache(this.nativeUrl) || this.nativeUrl;
- }
- this._skeletonCache = spine.initSkeletonData(uuid, filePath, atlasText, jsbTextures, this.scale);
- if (this._skeletonCache) {
- this.width = this._skeletonCache.getWidth();
- this.height = this._skeletonCache.getHeight();
- }
- };
- skeletonDataProto.recordTexture = function (texture) {
- const index = _gTextureIdx;
- const texKey = _textureKeyMap[index] = {
- key: index
- };
- _textureMap.set(texKey, texture);
- _gTextureIdx++;
- return index;
- };
- skeletonDataProto.getTextureByIndex = function (textureIdx) {
- const texKey = _textureKeyMap[textureIdx];
- if (!texKey) return null;
- return _textureMap.get(texKey);
- };
- const animation = spine.SkeletonAnimation.prototype; // The methods are added to be compatibility with old versions.
- animation.setCompleteListener = function (listener) {
- this._compeleteListener = listener;
- this.setCompleteListenerNative(function (trackEntry) {
- const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
- this._compeleteListener && this._compeleteListener(trackEntry, loopCount);
- });
- }; // The methods are added to be compatibility with old versions.
- animation.setTrackCompleteListener = function (trackEntry, listener) {
- this._trackCompeleteListener = listener;
- this.setTrackCompleteListenerNative(trackEntry, function (trackEntryNative) {
- const loopCount = Math.floor(trackEntryNative.trackTime / trackEntryNative.animationEnd);
- this._trackCompeleteListener && this._trackCompeleteListener(trackEntryNative, loopCount);
- });
- }; // Temporary solution before upgrade the Spine API
- animation.setAnimationListener = function (target, callback) {
- this._target = target;
- this._callback = callback; // eslint-disable-next-line no-undef
- const AnimationEventType = legacyCC.internal.SpineAnimationEventType;
- this.setStartListener(function (trackEntry) {
- if (this._target && this._callback) {
- this._callback.call(this._target, this, trackEntry, AnimationEventType.START, null, 0);
- }
- });
- this.setInterruptListener(function (trackEntry) {
- if (this._target && this._callback) {
- this._callback.call(this._target, this, trackEntry, AnimationEventType.INTERRUPT, null, 0);
- }
- });
- this.setEndListener(function (trackEntry) {
- if (this._target && this._callback) {
- this._callback.call(this._target, this, trackEntry, AnimationEventType.END, null, 0);
- }
- });
- this.setDisposeListener(function (trackEntry) {
- if (this._target && this._callback) {
- this._callback.call(this._target, this, trackEntry, AnimationEventType.DISPOSE, null, 0);
- }
- });
- this.setCompleteListener(function (trackEntry, loopCount) {
- if (this._target && this._callback) {
- this._callback.call(this._target, this, trackEntry, AnimationEventType.COMPLETE, null, loopCount);
- }
- });
- this.setEventListener(function (trackEntry, event) {
- if (this._target && this._callback) {
- this._callback.call(this._target, this, trackEntry, AnimationEventType.EVENT, event, 0);
- }
- });
- };
- const skeleton = cc.internal.SpineSkeleton.prototype;
- const AnimationCacheMode = cc.internal.SpineSkeleton.AnimationCacheMode;
- Object.defineProperty(skeleton, 'paused', {
- get() {
- return this._paused || false;
- },
- set(value) {
- this._paused = value;
- if (this._nativeSkeleton) {
- this._nativeSkeleton.paused(value);
- }
- }
- });
- Object.defineProperty(skeleton, 'premultipliedAlpha', {
- get() {
- if (this._premultipliedAlpha === undefined) {
- return true;
- }
- return this._premultipliedAlpha;
- },
- set(value) {
- this._premultipliedAlpha = value;
- if (this._nativeSkeleton) {
- this._nativeSkeleton.setOpacityModifyRGB(this._premultipliedAlpha);
- }
- }
- });
- Object.defineProperty(skeleton, 'timeScale', {
- get() {
- if (this._timeScale === undefined) return 1.0;
- return this._timeScale;
- },
- set(value) {
- this._timeScale = value;
- if (this._nativeSkeleton) {
- this._nativeSkeleton.setTimeScale(this._timeScale);
- }
- }
- });
- const _updateDebugDraw = skeleton._updateDebugDraw;
- skeleton._updateDebugDraw = function () {
- _updateDebugDraw.call(this);
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setDebugMeshEnabled(this.debugMesh);
- this._nativeSkeleton.setDebugSlotsEnabled(this.debugSlots);
- this._nativeSkeleton.setDebugBonesEnabled(this.debugBones);
- }
- };
- const _updateUseTint = skeleton._updateUseTint;
- skeleton._updateUseTint = function () {
- _updateUseTint.call(this);
- if (this._nativeSkeleton) {
- this._nativeSkeleton.setUseTint(this.useTint);
- }
- };
- skeleton._updateBatch = function () {
- if (this._nativeSkeleton) {
- this._renderEntity.setUseLocal(!this.enableBatch);
- this._nativeSkeleton.setBatchEnabled(this.enableBatch);
- this.markForUpdateRenderData();
- }
- };
- skeleton.setSkeletonData = function (skeletonData) {
- if (skeletonData.width != null && skeletonData.height != null) {
- const uiTrans = this.node._uiProps.uiTransformComp;
- uiTrans.setContentSize(skeletonData.width, skeletonData.height);
- }
- const uuid = skeletonData._uuid;
- if (!uuid) {
- cc.errorID(7504);
- return;
- }
- const texValues = skeletonData.textures;
- const texKeys = skeletonData.textureNames;
- if (!(texValues && texValues.length > 0 && texKeys && texKeys.length > 0)) {
- cc.errorID(7507, skeletonData.name);
- return;
- }
- if (this._nativeSkeleton) {
- this._nativeSkeleton.stopSchedule();
- this._nativeSkeleton._comp = null;
- this._nativeSkeleton = null;
- }
- let nativeSkeleton = null;
- if (this.isAnimationCached()) {
- nativeSkeleton = new spine.SkeletonCacheAnimation(uuid, this._cacheMode === AnimationCacheMode.SHARED_CACHE);
- } else {
- nativeSkeleton = new spine.SkeletonAnimation();
- try {
- spine.initSkeletonRenderer(nativeSkeleton, uuid);
- } catch (e) {
- cc._throw(e);
- return;
- }
- nativeSkeleton.setDebugSlotsEnabled(this.debugSlots);
- nativeSkeleton.setDebugMeshEnabled(this.debugMesh);
- nativeSkeleton.setDebugBonesEnabled(this.debugBones);
- }
- this._nativeSkeleton = nativeSkeleton;
- nativeSkeleton._comp = this;
- nativeSkeleton.setUseTint(this.useTint);
- nativeSkeleton.setOpacityModifyRGB(this.premultipliedAlpha);
- nativeSkeleton.setTimeScale(this.timeScale);
- nativeSkeleton.setBatchEnabled(this.enableBatch);
- const compColor = this.color;
- nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
- const materialTemplate = this.getMaterialTemplate();
- nativeSkeleton.setMaterial(materialTemplate);
- this._renderEntity.setUseLocal(!this.enableBatch);
- nativeSkeleton.setRenderEntity(this._renderEntity.nativeObj);
- this._skeleton = nativeSkeleton.getSkeleton(); // init skeleton listener
- this._startListener && this.setStartListener(this._startListener);
- this._endListener && this.setEndListener(this._endListener);
- this._completeListener && this.setCompleteListener(this._completeListener);
- this._eventListener && this.setEventListener(this._eventListener);
- this._interruptListener && this.setInterruptListener(this._interruptListener);
- this._disposeListener && this.setDisposeListener(this._disposeListener);
- this._sharedBufferOffset = nativeSkeleton.getSharedBufferOffset();
- this._useAttach = false;
- this.markForUpdateRenderData();
- };
- skeleton._updateColor = function () {
- if (this._nativeSkeleton) {
- const compColor = this.color;
- this._nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
- this.markForUpdateRenderData();
- }
- };
- skeleton.setAnimationStateData = function (stateData) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._stateData = stateData;
- this._nativeSkeleton.setAnimationStateData(stateData);
- }
- };
- const _onEnable = skeleton.onEnable;
- skeleton.onEnable = function () {
- if (_onEnable) {
- _onEnable.call(this);
- }
- if (this._nativeSkeleton) {
- this._nativeSkeleton.onEnable();
- }
- middleware.retain();
- };
- const _onDisable = skeleton.onDisable;
- skeleton.onDisable = function () {
- if (_onDisable) {
- _onDisable.call(this);
- }
- if (this._nativeSkeleton) {
- this._nativeSkeleton.onDisable();
- }
- middleware.release();
- };
- skeleton.setVertexEffectDelegate = function (effectDelegate) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setVertexEffectDelegate(effectDelegate);
- }
- }; // eslint-disable-next-line no-unused-vars
- skeleton.updateAnimation = function (dt) {
- const nativeSkeleton = this._nativeSkeleton;
- if (!nativeSkeleton) return;
- const node = this.node;
- if (!node) return;
- if (this.__preColor__ === undefined || !this.color.equals(this.__preColor__)) {
- const compColor = this.color;
- nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
- this.__preColor__ = compColor;
- }
- const socketNodes = this.socketNodes;
- if (!this._useAttach && socketNodes.size > 0) {
- this._useAttach = true;
- nativeSkeleton.setAttachEnabled(true);
- }
- if (!this.isAnimationCached() && (this.debugBones || this.debugSlots || this.debugMesh) && this._debugRenderer) {
- const graphics = this._debugRenderer;
- graphics.clear();
- graphics.lineWidth = 5;
- const debugData = this._debugData || nativeSkeleton.getDebugData();
- if (!debugData) return;
- let debugIdx = 0;
- let debugType = 0;
- let debugLen = 0;
- debugType = debugData[debugIdx++];
- while (debugType !== 0) {
- debugLen = debugData[debugIdx++];
- switch (debugType) {
- case 1:
- // slots
- graphics.strokeColor = _slotColor;
- for (let i = 0; i < debugLen; i += 8) {
- graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]);
- graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
- graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
- graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
- graphics.close();
- graphics.stroke();
- }
- break;
- case 2:
- // mesh
- graphics.strokeColor = _meshColor;
- for (let i = 0; i < debugLen; i += 6) {
- graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]);
- graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
- graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
- graphics.close();
- graphics.stroke();
- }
- break;
- case 3:
- // bones
- graphics.strokeColor = _boneColor;
- graphics.fillColor = _slotColor; // Root bone color is same as slot color.
- for (let i = 0; i < debugLen; i += 4) {
- const bx = debugData[debugIdx++];
- const by = debugData[debugIdx++];
- const x = debugData[debugIdx++];
- const y = debugData[debugIdx++]; // Bone lengths.
- graphics.moveTo(bx, by);
- graphics.lineTo(x, y);
- graphics.stroke(); // Bone origins.
- graphics.circle(bx, by, Math.PI * 1.5);
- graphics.fill();
- if (i === 0) {
- graphics.fillColor = _originColor;
- }
- }
- break;
- default:
- return;
- }
- debugType = debugData[debugIdx++];
- }
- }
- };
- skeleton.updateWorldTransform = function () {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.updateWorldTransform();
- }
- };
- skeleton.setToSetupPose = function () {
- if (this._nativeSkeleton) {
- this._nativeSkeleton.setToSetupPose();
- }
- };
- skeleton.setBonesToSetupPose = function () {
- if (this._nativeSkeleton) {
- this._nativeSkeleton.setBonesToSetupPose();
- }
- };
- skeleton.setSlotsToSetupPose = function () {
- if (this._nativeSkeleton) {
- this._nativeSkeleton.setSlotsToSetupPose();
- }
- };
- skeleton.setSlotsRange = function (startSlotIndex, endSlotIndex) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setSlotsRange(startSlotIndex, endSlotIndex);
- }
- };
- skeleton.updateAnimationCache = function (animName) {
- if (!this.isAnimationCached()) return;
- if (this._nativeSkeleton) {
- if (animName) {
- this._nativeSkeleton.updateAnimationCache(animName);
- } else {
- this._nativeSkeleton.updateAllAnimationCache();
- }
- }
- };
- skeleton.invalidAnimationCache = function () {
- if (!this.isAnimationCached()) return;
- if (this._nativeSkeleton) {
- this._nativeSkeleton.updateAllAnimationCache();
- }
- };
- skeleton.findBone = function (boneName) {
- if (this._nativeSkeleton) return this._nativeSkeleton.findBone(boneName);
- return null;
- };
- skeleton.findSlot = function (slotName) {
- if (this._nativeSkeleton) return this._nativeSkeleton.findSlot(slotName);
- return null;
- };
- skeleton.setSkin = function (skinName) {
- if (this._nativeSkeleton) return this._nativeSkeleton.setSkin(skinName);
- return null;
- };
- skeleton.getAttachment = function (slotName, attachmentName) {
- if (this._nativeSkeleton) return this._nativeSkeleton.getAttachment(slotName, attachmentName);
- return null;
- };
- skeleton.setAttachment = function (slotName, attachmentName) {
- this._nativeSkeleton && this._nativeSkeleton.setAttachment(slotName, attachmentName);
- }; // eslint-disable-next-line no-unused-vars
- skeleton.getTextureAtlas = function (regionAttachment) {
- cc.warn('Spine Skeleton getTextureAtlas not support in native');
- return null;
- };
- skeleton.setMix = function (fromAnimation, toAnimation, duration) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setMix(fromAnimation, toAnimation, duration);
- }
- };
- skeleton.setAnimation = function (trackIndex, name, loop) {
- const strName = name.toString();
- this._animationName = strName;
- this._playTimes = loop ? 0 : 1;
- let res = null;
- if (this._nativeSkeleton) {
- if (this.isAnimationCached()) {
- res = this._nativeSkeleton.setAnimation(strName, loop);
- } else {
- res = this._nativeSkeleton.setAnimation(trackIndex, strName, loop);
- }
- /**
- * note: since native spine animation update called after Director.EVENT_BEFORE_UPDATE
- * and before setAnimation. it's need to update native animation to first frame directly.
- */
- this._nativeSkeleton.update(0);
- }
- return res;
- };
- skeleton.addAnimation = function (trackIndex, name, loop, delay) {
- if (this._nativeSkeleton) {
- delay = delay || 0;
- if (this.isAnimationCached()) {
- return this._nativeSkeleton.addAnimation(name, loop, delay);
- } else {
- return this._nativeSkeleton.addAnimation(trackIndex, name, loop, delay);
- }
- }
- return null;
- };
- skeleton.findAnimation = function (name) {
- if (this._nativeSkeleton) return this._nativeSkeleton.findAnimation(name);
- return null;
- };
- skeleton.getCurrent = function (trackIndex) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- return this._nativeSkeleton.getCurrent(trackIndex);
- }
- return null;
- };
- skeleton.clearTracks = function () {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.clearTracks();
- }
- };
- skeleton.clearTrack = function (trackIndex) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.clearTrack(trackIndex);
- }
- };
- skeleton.setStartListener = function (listener) {
- this._startListener = listener;
- if (this._nativeSkeleton) {
- if (this.isAnimationCached()) {
- this._nativeSkeleton.setStartListener(function (animationName) {
- const self = this._comp;
- self._startEntry.animation.name = animationName;
- self._startListener && self._startListener(self._startEntry);
- });
- } else {
- this._nativeSkeleton.setStartListener(listener);
- }
- }
- };
- skeleton.setInterruptListener = function (listener) {
- this._interruptListener = listener;
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setInterruptListener(listener);
- }
- };
- skeleton.setEndListener = function (listener) {
- this._endListener = listener;
- if (this._nativeSkeleton) {
- if (this.isAnimationCached()) {
- this._nativeSkeleton.setEndListener(function (animationName) {
- const self = this._comp;
- self._endEntry.animation.name = animationName;
- self._endListener && self._endListener(self._endEntry);
- });
- } else {
- this._nativeSkeleton.setEndListener(listener);
- }
- }
- };
- skeleton.setDisposeListener = function (listener) {
- this._disposeListener = listener;
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setDisposeListener(listener);
- }
- };
- skeleton.setCompleteListener = function (listener) {
- this._completeListener = listener;
- if (this._nativeSkeleton) {
- if (this.isAnimationCached()) {
- this._nativeSkeleton.setCompleteListener(function (animationName) {
- const self = this._comp;
- self._endEntry.animation.name = animationName;
- self._completeListener && self._completeListener(self._endEntry);
- });
- } else {
- this._nativeSkeleton.setCompleteListener(listener);
- }
- }
- };
- skeleton.setEventListener = function (listener) {
- this._eventListener = listener;
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setEventListener(listener);
- }
- };
- skeleton.setTrackStartListener = function (entry, listener) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setTrackStartListener(entry, listener);
- }
- };
- skeleton.setTrackInterruptListener = function (entry, listener) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setTrackInterruptListener(entry, listener);
- }
- };
- skeleton.setTrackEndListener = function (entry, listener) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setTrackEndListener(entry, listener);
- }
- };
- skeleton.setTrackDisposeListener = function (entry, listener) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setTrackDisposeListener(entry, listener);
- }
- };
- skeleton.setTrackCompleteListener = function (entry, listener) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setTrackCompleteListener(entry, listener);
- }
- };
- skeleton.setTrackEventListener = function (entry, listener) {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- this._nativeSkeleton.setTrackEventListener(entry, listener);
- }
- };
- skeleton.getState = function () {
- if (this._nativeSkeleton && !this.isAnimationCached()) {
- return this._nativeSkeleton.getState();
- }
- return null;
- };
- skeleton._ensureListener = function () {
- cc.warn('Spine Skeleton _ensureListener not need in native');
- };
- skeleton._updateSkeletonData = function () {
- if (this.skeletonData) {
- this.skeletonData.init();
- this.setSkeletonData(this.skeletonData);
- this._indexBoneSockets();
- this.attachUtil.init(this);
- this._preCacheMode = this._cacheMode;
- this.defaultSkin && this._nativeSkeleton.setSkin(this.defaultSkin);
- this.animation = this.defaultAnimation;
- } else if (this._nativeSkeleton) {
- this._nativeSkeleton.stopSchedule();
- this._nativeSkeleton._comp = null;
- this._nativeSkeleton = null;
- }
- this._needUpdateSkeltonData = false;
- };
- const _onDestroy = skeleton.onDestroy;
- skeleton.onDestroy = function () {
- _onDestroy.call(this);
- if (this._nativeSkeleton) {
- this._nativeSkeleton.stopSchedule();
- this._nativeSkeleton._comp = null;
- this._nativeSkeleton = null;
- }
- this._stateData = null;
- };
- const _tempAttachMat4 = cc.mat4();
- skeleton._render = function () {
- const nativeSkeleton = this._nativeSkeleton;
- if (!nativeSkeleton) return;
- const socketNodes = this.socketNodes;
- if (socketNodes.size > 0) {
- const sharedBufferOffset = this._sharedBufferOffset;
- if (!sharedBufferOffset) return;
- const attachInfoMgr = middleware.attachInfoMgr;
- const attachInfo = attachInfoMgr.attachInfo;
- const attachInfoOffset = sharedBufferOffset[0]; // reset attach info offset
- sharedBufferOffset[0] = 0;
- for (const boneIdx of socketNodes.keys()) {
- const boneNode = socketNodes.get(boneIdx); // Node has been destroy
- if (!boneNode || !boneNode.isValid) {
- socketNodes.delete(boneIdx);
- continue;
- }
- const tm = _tempAttachMat4;
- const matOffset = attachInfoOffset + boneIdx * 16;
- tm.m00 = attachInfo[matOffset];
- tm.m01 = attachInfo[matOffset + 1];
- tm.m04 = attachInfo[matOffset + 4];
- tm.m05 = attachInfo[matOffset + 5];
- tm.m12 = attachInfo[matOffset + 12];
- tm.m13 = attachInfo[matOffset + 13];
- boneNode.matrix = tm;
- }
- }
- }; //////////////////////////////////////////
- // assembler
- const assembler = cc.internal.SpineAssembler; // eslint-disable-next-line no-unused-vars
- assembler.createData = function (comp) {};
- assembler.updateRenderData = function (comp) {
- comp._render();
- }; // eslint-disable-next-line no-unused-vars
- assembler.fillBuffers = function (comp, renderer) {};
- })();
- },{"./jsb-cache-manager":3}],13:[function(require,module,exports){
- /****************************************************************************
- Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- 'use strict';
- if (cc.internal.VideoPlayer) {
- const {
- EventType
- } = cc.internal.VideoPlayer;
- let vec3 = cc.Vec3;
- let mat4 = cc.Mat4;
- let _mat4_temp = new mat4();
- let _topLeft = new vec3();
- let _bottomRight = new vec3();
- cc.internal.VideoPlayerImplManager.getImpl = function (componenet) {
- return new VideoPlayerImplJSB(componenet);
- };
- class VideoPlayerImplJSB extends cc.internal.VideoPlayerImpl {
- constructor(componenet) {
- super(componenet);
- this._matViewProj_temp = new mat4();
- }
- syncClip(clip) {
- this.removeVideoPlayer();
- if (!clip) {
- return;
- }
- this.createVideoPlayer(clip._nativeAsset);
- }
- syncURL(url) {
- this.removeVideoPlayer();
- if (!url) {
- return;
- }
- this.createVideoPlayer(url);
- }
- onCanplay() {
- if (this._loaded) {
- return;
- }
- this._loaded = true;
- this.video.setVisible(this._visible);
- this.dispatchEvent(EventType.READY_TO_PLAY);
- this.delayedPlay();
- }
- _bindEvent() {
- this.video.addEventListener('loadedmetadata', this.onLoadedMetadata.bind(this));
- this.video.addEventListener('suspend', this.onCanPlay.bind(this));
- this.video.addEventListener('play', this.onPlay.bind(this));
- this.video.addEventListener('pause', this.onPause.bind(this));
- this.video.addEventListener('stoped', this.onStoped.bind(this));
- this.video.addEventListener('click', this.onClick.bind(this));
- this.video.addEventListener('ended', this.onEnded.bind(this));
- }
- onLoadedMetadata() {
- this._loadedMeta = true;
- this._forceUpdate = true;
- if (this._visible) {
- this.enable();
- } else {
- this.disable();
- }
- this.dispatchEvent(EventType.META_LOADED);
- this.delayedFullScreen();
- this.delayedPlay();
- }
- createVideoPlayer(url) {
- this._video = new jsb.VideoPlayer();
- this._bindEvent();
- this._video.setVisible(this._visible);
- this._video.setURL(url);
- this._forceUpdate = true;
- }
- removeVideoPlayer() {
- let video = this.video;
- if (video) {
- video.stop();
- video.setVisible(false);
- video.destroy();
- this._playing = false;
- this._loaded = false;
- this._loadedMeta = false;
- this._ignorePause = false;
- this._cachedCurrentTime = 0;
- this._video = null;
- }
- }
- getDuration() {
- if (!this.video) {
- return -1;
- }
- return this.video.duration();
- }
- syncPlaybackRate() {
- cc.warn('The platform does not support');
- }
- syncVolume() {
- cc.warn('The platform does not support');
- }
- syncMute() {
- cc.warn('The platform does not support');
- }
- syncLoop() {
- cc.warn('The platform does not support');
- }
- syncStayOnBottom() {
- cc.warn('The platform does not support');
- }
- getCurrentTime() {
- if (this.video) {
- this._cachedCurrentTime = this.video.currentTime();
- return this._cachedCurrentTime;
- }
- return -1;
- }
- seekTo(val) {
- let video = this._video;
- if (!video) return;
- video.seekTo(val);
- this._cachedCurrentTime = val;
- }
- disable(noPause) {
- if (this.video) {
- if (!noPause) {
- this.video.pause();
- }
- this.video.setVisible(false);
- this._visible = false;
- }
- }
- enable() {
- if (this.video) {
- this.video.setVisible(true);
- this._visible = true;
- }
- }
- canPlay() {
- this.video.play();
- this.syncCurrentTime();
- }
- resume() {
- if (this.video) {
- this.video.resume();
- this.syncCurrentTime();
- this._playing = true;
- }
- }
- pause() {
- if (this.video) {
- this._cachedCurrentTime = this.video.currentTime();
- this.video.pause();
- }
- }
- stop() {
- if (this.video) {
- this._ignorePause = true;
- this.video.seekTo(0);
- this._cachedCurrentTime = 0;
- this.video.stop();
- }
- }
- canFullScreen(enabled) {
- if (this.video) {
- this.video.setFullScreenEnabled(enabled);
- }
- }
- syncKeepAspectRatio(enabled) {
- if (this.video) {
- this.video.setKeepAspectRatioEnabled(enabled);
- }
- }
- syncMatrix() {
- if (!this._video || !this._component || !this._uiTrans) return;
- const camera = this.UICamera;
- if (!camera) {
- return;
- }
- this._component.node.getWorldMatrix(_mat4_temp);
- const {
- width,
- height
- } = this._uiTrans.contentSize;
- 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) {
- return;
- }
- this._matViewProj_temp.set(camera.matViewProj); // update matrix cache
- 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;
- let canvas_width = cc.game.canvas.width;
- let canvas_height = cc.game.canvas.height;
- let ap = this._uiTrans.anchorPoint; // Vectors in node space
- vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
- vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0); // Convert to world space
- vec3.transformMat4(_topLeft, _topLeft, _mat4_temp);
- vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp); // need update camera data
- camera.update(); // Convert to Screen space
- camera.worldToScreen(_topLeft, _topLeft);
- camera.worldToScreen(_bottomRight, _bottomRight);
- let finalWidth = _bottomRight.x - _topLeft.x;
- let finalHeight = _topLeft.y - _bottomRight.y;
- this._video.setFrame(_topLeft.x, canvas_height - _topLeft.y, finalWidth, finalHeight);
- this._forceUpdate = false;
- }
- }
- }
- },{}],14:[function(require,module,exports){
- /****************************************************************************
- Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
- https://www.cocos.com/
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- 'use strict';
- if (cc.internal.WebView) {
- const {
- EventType
- } = cc.internal.WebView;
- let vec3 = cc.Vec3;
- let mat4 = cc.Mat4;
- let _mat4_temp = new mat4();
- let _topLeft = new vec3();
- let _bottomRight = new vec3();
- cc.internal.WebViewImplManager.getImpl = function (componenet) {
- return new WebViewImplJSB(componenet);
- };
- class WebViewImplJSB extends cc.internal.WebViewImpl {
- constructor(componenet) {
- super(componenet);
- this.jsCallback = null;
- this.interfaceSchema = null;
- this._matViewProj_temp = new mat4();
- }
- _bindEvent() {
- let onLoaded = () => {
- this._forceUpdate = true;
- this.dispatchEvent(EventType.LOADED);
- };
- let onError = () => {
- this.dispatchEvent(EventType.ERROR);
- };
- this.webview.setOnDidFinishLoading(onLoaded);
- this.webview.setOnDidFailLoading(onError);
- this.jsCallback && this.setOnJSCallback(this.jsCallback);
- this.interfaceSchema && this.setJavascriptInterfaceScheme(this.interfaceSchema); // remove obj
- this.jsCallback = null;
- this.interfaceSchema = null;
- }
- createWebView() {
- if (!jsb.WebView) {
- console.warn('jsb.WebView is null');
- return;
- }
- this._webview = jsb.WebView.create();
- this._bindEvent();
- }
- removeWebView() {
- let webview = this.webview;
- if (webview) {
- this.webview.destroy();
- this.reset();
- }
- }
- disable() {
- if (this.webview) {
- this.webview.setVisible(false);
- }
- }
- enable() {
- if (this.webview) {
- this.webview.setVisible(true);
- }
- }
- setOnJSCallback(callback) {
- let webview = this.webview;
- if (webview) {
- webview.setOnJSCallback(callback);
- } else {
- this.jsCallback = callback;
- }
- }
- setJavascriptInterfaceScheme(scheme) {
- let webview = this.webview;
- if (webview) {
- webview.setJavascriptInterfaceScheme(scheme);
- } else {
- this.interfaceSchema = scheme;
- }
- }
- loadURL(url) {
- let webview = this.webview;
- if (webview) {
- webview.src = url;
- webview.loadURL(url);
- this.dispatchEvent(EventType.LOADING);
- }
- }
- evaluateJS(str) {
- let webview = this.webview;
- if (webview) {
- return webview.evaluateJS(str);
- }
- }
- syncMatrix() {
- if (!this._webview || !this._component || !this._uiTrans) return;
- const camera = this.UICamera;
- if (!camera) {
- return;
- }
- this._component.node.getWorldMatrix(_mat4_temp);
- const {
- width,
- height
- } = this._uiTrans.contentSize;
- 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) {
- return;
- }
- this._matViewProj_temp.set(camera.matViewProj); // update matrix cache
- 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;
- let canvas_width = cc.game.canvas.width;
- let canvas_height = cc.game.canvas.height;
- let ap = this._uiTrans.anchorPoint; // Vectors in node space
- vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
- vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0); // Convert to world space
- vec3.transformMat4(_topLeft, _topLeft, _mat4_temp);
- vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp); // need update camera data
- camera.update(); // Convert to Screen space
- camera.worldToScreen(_topLeft, _topLeft);
- camera.worldToScreen(_bottomRight, _bottomRight);
- let finalWidth = _bottomRight.x - _topLeft.x;
- let finalHeight = _topLeft.y - _bottomRight.y;
- this._webview.setFrame(_topLeft.x, canvas_height - _topLeft.y, finalWidth, finalHeight);
- this._forceUpdate = false;
- }
- }
- }
- },{}]},{},[1]);
|