engine-adapter.js 164 KB

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